簡體   English   中英

如何從html中的textarea獲取輸入到Angular中的.ts

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM