Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accessing FormControl in Angular 2

Tags:

angular

What is the difference between template variable spy and name in following two statements? What does spy represent and what does name represent. The code is from following tutorial on Angular.

https://angular.io/docs/ts/latest/guide/forms.html

<input type="text" class="form-control" id="name"
  required
  [(ngModel)]="model.name" name="name"
  #spy>
<br>TODO: remove this: {{spy.className}}
spy is assigned value of control which represents the input.



<input type="text" class="form-control" id="name"
               required
               [(ngModel)]="model.name" name="name"
               #name="ngModel">

I thought that spy represents the FormControl within NgForm to represent the input element. Using spy, I can access properties of the FormControl (eg spyu.className). But I couldn't understand if name is also a FormControl and how assigning it a value of "ngModel" makes it different from spy

like image 262
Manu Chadha Avatar asked Sep 09 '26 03:09

Manu Chadha


1 Answers

What does spy represent

When you specify template reference by itself like this #some-name, it by default references ElementRef in a component/directive class and native DOM element in the template. ElementRef is a wrapper around native DOM element and you can read more about it here. className is a standard DOM API that is a string of all classes attached to the element.

If it's used by itself on the child component, it by default references component instance.

what does name represent

When you specify template reference in the form #some-name="other-name", it references a directive by the name other-name. So in your case:

#name="ngModel"

it references NgModel directive instance on this input control.

I thought that spy represents the FormControl within NgForm to represent the input element.

No, as I explained earlier, it represents ElementRef. To get access to the form control through template reference, you would have to use FormControlDirective and use template reference like this:

<input #spy="ngForm" [formControl]="control">

As this directive is defined like this:

@Directive({selector: '[formControl]', providers: [formControlBinding], exportAs: 'ngForm'})

                                      ---------------------------------------- ^^^^^^^^^

export class FormControlDirective extends NgControl implements OnChanges {

But that wouldn't make much sense as you would already have access to the form control in your component control value.

like image 72
Max Koretskyi Avatar answered Sep 11 '26 19:09

Max Koretskyi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!