5

I have a simple app which adds the textbox value to listbox when enter key is pressed in textbox. Here is my html code

<input type="text" value="{{ myText }}" (keypress)="keyEvent($event)"  /> 
<select multiple="multiple" >
  <option *ngFor="let item of itemsList">
    {{item}} 
  </option>
</select>

here is my typescript component code

export class AppComponent {
  title = `hello world app !`;
  myText ='';
  itemsList = [];constructor() { 
  }

  ngOnInit() {
  }

  keyEvent(event)
  {
    if(event.keyCode === 13)
    {
      event.preventDefault(); // Otherwise the form will be submitted
      this.itemsList.push(this.myText);
    }
  }

myText value is not getting updated . the value is always null.

Please help to figure out what is that i am missing while binding myText.

1 Answer 1

9

It's not updating because you need TWO WAY data binding via ngModel:

<input type="text" [(ngModel)]="myText" (keypress)="keyEvent($event)" /> 

For more info: https://angular.io/api/forms/NgModel

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

5 Comments

after adding [(ngModel)]="myText" html page goes blank :(
@Comercial Suicide No errors .. when i remove the outer braces atleast the screen is visible but still the binding doesnt happen ----------- like this.(ngModel)="myText"
@Peekay, the ngModels two way binding will work only with "banana in box" notation [()]. Sorry, I can't really say why you're getting the blank page when using [(ngModel)] without live example =(
@Peekay, what is the p attribute on your input?
@Peekay you need to add imports in component.ts import { NgModel , NgForm } from '@angular/forms';

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.