2

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 ;
}
3
  • Is it angular or angularJS? In angular you have to use [(ngModel)]="num1" Commented Feb 20, 2020 at 3:11
  • you are mixing angular and angularJS. The click event is called using angular syntax. In angularJS, it should be ng-click="onSelectEqual()" - docs.angularjs.org/api/ng/directive/ngClick. Commented Feb 20, 2020 at 3:28
  • 1
    A gentle reminder: AngularJS == versions 1.x; Angular == versions 2+. There is no such thing as AngularJS 8. Commented Feb 20, 2020 at 3:34

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.