Angular Forms – A Guide to Learning Angular (Part 7)

Posted by


Forms in Angular are an essential aspect of building dynamic and interactive web applications. In this tutorial, we will dive deep into forms in Angular and learn how to create and work with them effectively.

There are two types of forms in Angular, template-driven forms, and reactive forms. In this tutorial, we will focus on template-driven forms as they are easier to understand and implement for beginners. Template-driven forms rely on directives in the template to create and manage form controls. Reactive forms, on the other hand, are more flexible and powerful but require a more complex setup.

To get started with forms in Angular, we first need to create a new Angular project. If you have not already set up an Angular project, you can do so by running the following command in your terminal:

ng new my-project

Once your project is set up, navigate to the project directory and open it in your code editor. To create a new form in Angular, we need to first import the FormsModule module in the app.module.ts file. Add the following import statement at the top of the file:

import { FormsModule } from '@angular/forms';

Next, add the FormsModule module to the imports array in the @NgModule decorator:

@NgModule({
  imports: [
    // other modules
    FormsModule
  ]
})

Now we can create a new form in our component template. Open the app.component.html file and add the following code:

<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name" ngModel required>

  <label for="email">Email:</label>
  <input type="email" id="email" name="email" ngModel required email>

  <button type="submit">Submit</button>
</form>

In this form, we are using the ngForm directive to create a new form instance and the ngModel directive to bind form controls to properties in our component. We also added the required and email validators to the email input field.

Next, open the app.component.ts file and add the following code to handle form submission:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  onSubmit(form: NgForm) {
    if (form.valid) {
      console.log(form.value);
    }
  }
}

In this code, we created a method called onSubmit that takes the form instance as an argument. We check if the form is valid before logging the form values to the console.

Finally, to display form validation errors in the template, we can use the following code:

<div *ngIf="myForm.controls['name'].invalid && myForm.controls['name'].touched">
  <p>Name is required.</p>
</div>
<div *ngIf="myForm.controls['email'].invalid && myForm.controls['email'].touched">
  <p>Email is required and must be a valid email address.</p>
</div>

In this code, we are using the *ngIf directive to conditionally display error messages based on the validity and touch state of the form controls.

And that’s it! You have now successfully created a template-driven form in Angular. You can further customize and enhance your form by adding more form controls, validators, and error messages.

In conclusion, forms are an essential part of building interactive web applications in Angular. By following this tutorial, you should now have a good understanding of how to create and work with template-driven forms in Angular. Remember to practice and experiment with different form features to become more proficient in working with forms in Angular.

0 0 votes
Article Rating

Leave a Reply

18 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@Angular
3 hours ago

Watch more episodes of Learning Angular→ https://goo.gle/Learning-Angular

@mirandelass
3 hours ago

love u Mark my brother

@HatchettTheGreat
3 hours ago

Sheesh how do you code with that ide theme lol

@Centrifuze
3 hours ago

Dunno if this is a version issue or not, but at 5:29, I needed to add in </form> between the button and </section>.

@NaomiNos
3 hours ago

I'm getting Can't bind to 'submit' since it isn't a known property of 'form'.ngtsc(-998002) and it doesn't let me to use [submit] in brackets. Removing [] doesn't do anything.

@teemusekki1743
3 hours ago

I add some console.log in getHousingLocationById and seems that function got right parameter. ERROR Error: Uncaught (in promise): InvalidCharacterError: String contains an invalid character…first line of console error

@teemusekki1743
3 hours ago

I don't have any clue about Angular debuging since I'm just starter. But it seems that after clicking Learn more I have some kind a parsing error but in vscode doesn't show any errors and yesterday it worked before adding form. So I asume that have some mistakes in my form but it seems similar that this example.

@teemusekki1743
3 hours ago

After adding form I got error this again <a [routerLink]="['/details', housingLocation.id]">Learn more</a>. Some kind parse error

@Himanshubishnoi-td3nh
3 hours ago

Angular make Java Brains angular Playlist as your default video documentation.

@djrandomoficial4901
3 hours ago

Kd os BR

@diprefranco
3 hours ago

5:38 best part

@ShawnTalbert-k2u
3 hours ago

This should have been about template driven forms. So called 'reactive' forms are a step backwards for webdev IMHO and more complicated.

@gillesashley9314
3 hours ago

As a React developer, I wanted to learn Angular, but this series just killed my morale, Angular is overwhelming. It has so many part you need to understand.

@pogchamper228
3 hours ago

5:31 close the "form" tag.

@kushansumanaweera7086
3 hours ago

time stamp 05.31, you forgot to close form tag </form>

@MarfTaylor
3 hours ago

hello there, what happens if I have the form component separated from the app component, do I need to pass the classes again to the imports array ?

@jediampm
3 hours ago

Hi,
again inline template too big, it should be in separate file.
Or at least the form should be in a new component and you could take advantage to teach how emit events.

Like in Angular docs, here in this video, for a form so simple and without validation make no sense use / teach reactive form for beginners.
A template driven form or even without it would be enough. This way some junior dev or other devs that use other frameworks think that Angular learning curve is big. Because in tutorial for beginners you are teach advance things like reactive forms. This is valid form this tutorial and for Angular docs.

So please start and keep it simple.
Thanks you.😥

@albrough
3 hours ago

@4:52, should it not be <label for=last-name">?

18
0
Would love your thoughts, please comment.x
()
x