Angular

Last Updated: 8/28/2023

ngModel

  • Applying ngModel directive in the input field without any binding will create a control object and associate with the input field under the hood
  • ngModel requires name attribute in the input field, a way to distinguish the control objects
<input type="text" ngModel>  -- error either name must be set or formcontrol must be defined as standalone
  • In template driven approach, add ngModel and set name attribute
<input type="text" ngModel name="firstName">
  • Create a template variable and sets it to ngModel directive
<input type="text" ngModel name="firstName" id="firstName" #firstName="ngModel" (change)="console.log(firstName)">
  • Formcontrol is used to track state changes and the validity of the input fields
  • Why "ngModel"? A directive's exportAs property tells Angular how to link the reference variable to the directive. You set name to ngModel because the ngModel directive's exportAs property happens to be "ngModel".