[英]How to get input from textarea in html to .ts in Angular
我是 Angular 的新手,现在我想从 textarea 获取用户输入,但我没有这样做。
更新:ng-model="num1" > [(ngModel)]="num1"
HTML:
<span><input [(ngModel)]="num1" type="text" placeholder="Enter value"></span>
// user enter one number
<span><input type="text" readonly value={{answer}}></span></p>
<button class="result" (click)=onSelectEqual()>=</button>
// click this button to get the value that user entered
.ts:
num1 : number;
answer: number;
onSelectEqual(){
this.answer = this.num1 + 1 ;
}
在 angular 中,对于two-way binding
您必须将ngModel
在[()]
。 请参阅 - https://angular.io/api/forms/NgModel 。
<span><input [(ngModel)]="num1" type="text" placeholder="Enter value"></span>
在 html 模板中使用[(ngModel)]
而不是 ng-model。 ng-model 是 Angularjs 的语法,它在 Angular2+ 中不起作用。
另外,还要确保导入FormsModule
在app.module.ts
import { FormsModule } from '@angular/forms';
还将它添加到 app.module.ts 中的导入数组
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
这很重要,因为没有 FormsModule,angular 将无法识别 ngModel 指令。
另一方面,输入将返回用户键入的值作为字符串。 要将其读取为数字并为其加 1,您必须对其进行类型转换:
onSelectEqual(){
this.answer = Number(this.num1) + 1 ;
}
另请注意, //
用于注释在 html 模板中不起作用,请改用<!-- -->
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.