[英]How to get input from textarea in html to .ts in Angular
I am a newbie in Angular and now I want to get user input from a textarea but I fail to do so.我是 Angular 的新手,现在我想从 textarea 获取用户输入,但我没有这样做。
Updated: ng-model="num1" > [(ngModel)]="num1"更新:ng-model="num1" > [(ngModel)]="num1"
HTML: 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: .ts:
num1 : number;
answer: number;
onSelectEqual(){
this.answer = this.num1 + 1 ;
}
In angular, for two-way binding
you have to enclose ngModel
in [()]
.在 angular 中,对于
two-way binding
您必须将ngModel
在[()]
。 See - https://angular.io/api/forms/NgModel .请参阅 - https://angular.io/api/forms/NgModel 。
<span><input [(ngModel)]="num1" type="text" placeholder="Enter value"></span>
Use [(ngModel)]
instead of ng-model in your html template.在 html 模板中使用
[(ngModel)]
而不是 ng-model。 ng-model is the syntax of Angularjs which will not work in Angular2+. ng-model 是 Angularjs 的语法,它在 Angular2+ 中不起作用。
Also make sure to import FormsModule
in app.module.ts另外,还要确保导入
FormsModule
在app.module.ts
import { FormsModule } from '@angular/forms';
Also add it to the imports array in app.module.ts还将它添加到 app.module.ts 中的导入数组
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
This is important as without the FormsModule, angular will not be able to identify the ngModel directive.这很重要,因为没有 FormsModule,angular 将无法识别 ngModel 指令。
On a different note, the input will return the value typed by the user as a string.另一方面,输入将返回用户键入的值作为字符串。 To read it as a number and add 1 to it, you will have to typecast it:
要将其读取为数字并为其加 1,您必须对其进行类型转换:
onSelectEqual(){
this.answer = Number(this.num1) + 1 ;
}
Please also note that //
for comments doesn't work in html template, use <!-- -->
instead.另请注意,
//
用于注释在 html 模板中不起作用,请改用<!-- -->
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.