I am a newbie in Angular and now I want to get user input from a textarea but I fail to do so.
Updated: 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 ;
}
In angular, for two-way binding
you have to enclose ngModel
in [()]
. See - 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. ng-model is the syntax of Angularjs which will not work in Angular2+.
Also make sure to import FormsModule
in app.module.ts
import { FormsModule } from '@angular/forms';
Also add it to the imports array in app.module.ts
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
This is important as without the FormsModule, angular will not be able to identify the ngModel directive.
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:
onSelectEqual(){
this.answer = Number(this.num1) + 1 ;
}
Please also note that //
for comments doesn't work in html template, use <!-- -->
instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.