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"?