lets assume the app component has defined the variable for the value in the input but every time the event for the button has been triggered the string is printed at empty and the binding doesnt seem to work at all
export class AppComponent {
numVal =1235;
cssClass= 'hello';
title = 'AngularAppTest';
textVal:String='';
onClickBtn(){
console.log(this.textVal);
}
}
and the html can be either this
<input type="text" value={{textVal}} />
<button (click)="onClickBtn()">Check Binding</button>
<span style="display: block;">Value: {{textVal}}</span>
or
<input type="text" [value]=textVal />
<button (click)="onClickBtn()">Check Binding</button>
<span style="display: block;">Value: {{textVal}}</span>
Below is my best representation for you to understand binding,
[value] <- update html from ts (single binding)
(value) <- update ts from html (single binding)
[(value)] <- update ts from html and vice versa (double binding)
ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
numVal = 1235;
cssClass = 'hello';
title = 'AngularAppTest';
textVal: String = '';
textVal2: String = '';
textVal3: String = '';
textVal4: String = 'asdf';
onClickBtn() {
console.log(this.textVal);
}
onClickBtn1() {
console.log(this.textVal);
}
onClickBtn2() {
console.log(this.textVal);
}
onClickBtn3() {
console.log(this.textVal);
}
updateValue(event) {
this.textVal2 = event.target.value;
}
updateValue3(event) {
this.textVal4 = event.target.value;
}
updateValue2(value) {
console.log(value);
this.textVal3 = value;
}
}
html
<!-- double binding -->
<input type="text" [(ngModel)]="textVal" />
<button (click)="onClickBtn()">Check Binding</button>
<span style="display: block;">Value: {{ textVal }}</span>
<!-- single binding updating model with event wihtout ngmodel -->
<input type="text" [value]="textVal2" (input)="updateValue($event)" />
<button (click)="onClickBtn2()">Check Binding</button>
<span style="display: block;">Value: {{ textVal2 }}</span>
<!-- single binding updating model with event with ngmodel and ngmodelchange-->
<input
type="text"
[ngModel]="textVal3"
(ngModelChange)="updateValue2($event)"
/>
<button (click)="onClickBtn3()">Check Binding</button>
<span style="display: block;">Value: {{ textVal3 }}</span>
<!-- single binding updating model with event with double quotes-->
<input type="text" value="{{ textVal4 }}" (input)="updateValue3($event)" />
<button (click)="onClickBtn4()">Check Binding</button>
<span style="display: block;">Value: {{ textVal4 }}</span>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments