我的 Angular 代码是否正确? (事件绑定)
Is my Angular code for correct? (event binding)
app.component.html
<input (keypress)="degistir($event)" />
<div> {{isim}} </div>
app.component.ts
isim: string = "";
degistir(event:any){
this.isim = event.target.value;
}
预览:
这是正确的。
<input (keypress) = "degistir($event)" />
<div> {{isim}} </div>
isim: string ="";
degistir(event: KeyboardEvent){
this.isim= event.target.value;
你可以编写更多类型安全的代码
degistir(event:KeyboardEvent){
this.isim = (<HTMLInputElement>event.target).value;
}
或者如果你想检查每个按下的键,你可以使用下面的代码片段
degistir(event:KeyboardEvent){
this.isim = event.key;
}
您的代码运行良好,但它是对还是错取决于您希望代码的明确程度。我下面的代码和你的一样好,但更明确。
<input (keypress) = "degistir($event)" />
<div> {{isim}} </div>
public isim: any; //converted to 'any' type because we don't know user input
degistir(event: KeyboardEvent): void { // typeof event is 'KeyboardEvent' and function is type of void
this.isim = event.target.value;
}
app.component.html
<input (keypress)="degistir($event)" />
<div> {{isim}} </div>
app.component.ts
isim: string = "";
degistir(event:any){
this.isim = event.target.value;
}
预览:
这是正确的。
<input (keypress) = "degistir($event)" />
<div> {{isim}} </div>
isim: string ="";
degistir(event: KeyboardEvent){
this.isim= event.target.value;
你可以编写更多类型安全的代码
degistir(event:KeyboardEvent){
this.isim = (<HTMLInputElement>event.target).value;
}
或者如果你想检查每个按下的键,你可以使用下面的代码片段
degistir(event:KeyboardEvent){
this.isim = event.key;
}
您的代码运行良好,但它是对还是错取决于您希望代码的明确程度。我下面的代码和你的一样好,但更明确。
<input (keypress) = "degistir($event)" />
<div> {{isim}} </div>
public isim: any; //converted to 'any' type because we don't know user input
degistir(event: KeyboardEvent): void { // typeof event is 'KeyboardEvent' and function is type of void
this.isim = event.target.value;
}