1

I am learning Angular on Pluralsight and I have a question regarding a course I am taking currently.

I am confused on the reasoning behind template reference variables when they are assigned a value. For example, if you put #name in an <input> tag, I understand name can now reference the input tag and it's associated value. The question I have is regarding decalrations such as #name="ngModel"

Looking over the Angular documentation, I found this:

You need a template reference variable to access the input box's Angular control from within the template. Here you created a variable called name and gave it the value "ngModel".

I also found this helpful answer to guide me on the right track.

But I am still a bit unclear as to what value assigning the template reference variable ngModel adds.

Part of the form I am currently writing:

<form #form="ngForm" (ngSubmit)="onSubmit(form)">

        <div class="form-group">
            <label for="name">Name</label>
            <input id="name" name="name" class="form-control" [(ngModel)]="userSettings.name"
                    required #nameField="ngModel"
                    (blur)="onBlur(nameField)"
                    [class.field-error]="form.submitted && nameField.invalid">
            <div [hidden]="!form.submitted || nameField.valid"
                class="alert alert-danger">
                Enter a name
            </div>
        </div>

Part of the Typescript file:

@Component({
  selector: 'app-user-settings-form',
  templateUrl: './user-settings-form.component.html',
  styleUrls: ['./user-settings-form.component.css']
})
export class UserSettingsFormComponent implements OnInit {

  originalUserSettings: UserSettings = {
    name: null,
    emailOffers: null,
    interfaceStyle: null,
    subscriptionType: null,
    notes: null
  };

  userSettings: UserSettings = { ...this.originalUserSettings };

  constructor() { }

  ngOnInit(): void {

  }

What is the difference between just using #nameField vs using #nameField="ngModel" as well as #form vs #form="ngForm"?

PhillyD
  • 181
  • 1
  • 18

1 Answers1

1

I am not sure which documentation did you have a look at but you can have a look here => https://angular.io/guide/template-syntax#input-and-output-properties

The short answer is that normally you would declare template variables without assigning a name to them => #variable <= and this will give you access to the html element and its value. In some rare cases as is in the case with the ngForm and ngModel which are called directives, they will give you for example the ability to track the value and validity of every control in the form => ngForm.

Ivan Mihaylov
  • 434
  • 2
  • 9