Template Variables
- To access the value of the input from template
Using event object
<input (keyup.enter)="onKeyUp($event)">
onKeyUp($event) {
console.log($event.target.value);
}
Using template variable
- Template Variable: Declare a variable in the template that references the input
<input #email (keyup.enter)="onKeyUp(email.value)">
Two-way Binding
- Property binding is one way from component to view
- Passing parameters to the method is procedural programming, instead use the data of the object using this keyword
Option 1 using template variable
component.html
<input [value]="email" (keyup.enter)="email = $event.target.value; onKeyUp()">
component.ts
email = "abc@domain.com";
onKeyUp() {
console.log(this.email)
}
Option 2 - using ngModel
- Use
ngModel
directive for implementing two way binding
- Angular framework consist of several different modules. In every module, we have bunch of building blocks that are highly related. component, directives, pipes etc. Not every app requires all the module in angular. When you bring all modules. it will increase code size
ngModel
directive is defined in formsModule. Import that module
- Add forms module in the imports of app module
import {FormsModule} from '@angular/forms'
app.module.ts
imports: [FormsModule]
<input [(ngModel)]="email" (keyup.enter)="onKeyUp()">
email = "abc@domain.com";
onKeyUp() {
console.log(email)
}