Angular 我的角度代码正确吗?(事件绑定)
app.component.htmlAngular 我的角度代码正确吗?(事件绑定),angular,typescript,angular10,Angular,Typescript,Angular10,app.component.html {{isim}} app.component.ts isim:string=”“; 除气器(事件:任何){ this.isim=event.target.value; } 预览: 这是正确的 <input (keypress) = "degistir($event)" /> <div> {{isim}} </div> 您可以编写更多类型安全代码 degistir(event:Keyboar
{{isim}}
app.component.ts
isim:string=”“;
除气器(事件:任何){
this.isim=event.target.value;
}
预览:
这是正确的
<input (keypress) = "degistir($event)" />
<div> {{isim}} </div>
您可以编写更多类型安全代码
degistir(event:KeyboardEvent){
this.isim = (<HTMLInputElement>event.target).value;
}
您的代码运行良好,但它是否正确取决于您希望代码的显式程度。我下面的代码和你的一样好,但它更明确
<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;
}
{{isim}}
公共isim:任何//已转换为“任意”类型,因为我们不知道用户输入
degistir(event:KeyboardEvent):void{//typeof事件为'KeyboardEvent',函数为void类型
this.isim=event.target.value;
}
src/app/app.component.ts:15:29中的错误-错误TS2339:类型“EventTarget”上不存在属性“value”。15这个.isim=event.target.value~~~~~<代码>degistir(事件:KeyboardEvent):void{this.isim=event;}
感谢您的帮助我的代码运行正常,但缺少一封信。为什么在这里不需要将isim
变量标记为public
,因为您的组件在Angular以外的任何地方都不可用。keyup和keypress之间的区别是什么?keypress–在按下某个键时触发,keyup–在释放任何键后触发
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;
}