...

/

The Built-in `NgModel` Directive

The Built-in `NgModel` Directive

Let’s learn about `NgModel`, a built-in attribute directive.

The NgModel directive is an attribute directive. However, contrary to the previous two directives, NgClass and NgStyle, it does not change the appearance. Instead, it changes the behavior of the applied element.

Why NgModel is useful?

Whenever we have to implement a template-driven form, the NgModel is very helpful. It creates a two-way data binding for writing and reading values that are assigned to a particular control.

Template-driven forms

In Angular, there are two approaches listed below for designing the concept of a form:

  • Template-driven forms
  • Reactive forms

Template-driven forms rely mostly on implementing a template where the controls are handled through provided directives. One of them is the NgModel. It’s better to use this type of design instead of basic types of forms. This is because these designs are easier to set up. If we don’t have any complex logic or scalability issues, we can use template-driven forms.

Here’s a short example of what that would look like:

@Component({
  selector: 'app-form',
  template: `Your name: <input type="text" value="John" >`,
})
export class FormComponent {  
}

On the other hand, reactive forms provide a far more advanced way of handling the form. This design moves the logic from the template into the component’s class. There, we can set up the whole form along with the custom logic so that we can validate, set, and receive values. We can also reactively control the state and form value. Reactive forms are a perfect choice for more complex, scalable forms.

Here’s a short example of how to use a reactive form:

 ...