Hello I have recently ventured into angular and ionic development.
I understand that interpolation and property binding is to pass data from class to template, and that interpolation supports only strings, whereas property binding supports all types.
Event binding is used to pass data from template into class.
Two way binding is achieved using foll. 4 ways:
- With ngModel banana syntax:
<input [(ngModel)]="username"> <p>Hello {{username}}!</p>
- NgModel without banana syntax:
<input [ngModel]="username" (ngModelChange)="username = $event"> <p>Hello {{username}}!</p>
- Without ngModel:
<input [value]="username" (input)="username = $event.target.value"> <p>Hello {{username}}!</p>
Or
<input [value]="username" (input)="username = varTest.value" #varTest> <p>Hello {{username}}!</p>
- We can implement custom two way binding (without ngModel) provided we implement appropriate functions:
<custom-counter [(counter)]="someValue"></custom-counter> <p>counterValue = {{someValue}}</p>
We also have a concept of template reference variables. When you declare this on say an input field, the value of field is accessible in the template using interpolation. Also, if ngModel is assigned to template ref variable.. #varTref="ngModel", then various properties of the element like validation, dirty, pristine, touched, untouched is accessible in template using interpolation. All these can be passed to the code class file by passing the template ref variable into say for example a button click event OR we can make use of ViewChild concept.
My question is about ngForms and ngModel concept in case of forms (template driven forms):
We use
<form #f="ngForm".....
And then in each input element we use ngModel with a name and this makes it accessible as property of forms.value.fieldname. Can the same thing not be achieved just by using template reference variable and then passing this to the button click event, thus having access to the form elements in the code? Then why do we have to use ngForm concept?At element level we use ngModel. Is this same as attribute binding or event binding? Or is it just to make the element accessible to the #f? We could as well use template reference variable to achieve the same isnt it? To achieve two way binding we make use of banana syntax here too so what purpose does just using the keyword ngModel at every element level really serve in template driven forms?
Is using [(ngModel)]=varName same as writing [(ngModel)] name=varName?
Please I need some clarity in this. Thanks.