2

I faced a problem with ngModel directive. I have an input <td><input type="text" ([ngModel])="desc"></td> in which I assigned value of that input to the variable called desc. Then in component I just want to print it in the console by:

addItem(){
    console.log('=======', this.desc);
  }

The method addItem() is decalred in html file below the input:

   <td>
            <i
              class="fa fa-plus-square add-button"
              (click)="addItem()">
            </i>
   </td>

The thing which I get back is: ======= undefined in the console. Can anyone tell me why I got this? In diffrent place of this app I'm also using ngModel and everything works good

1 Answer 1

2

The syntax of the data-binding operators ( and [ is wrong, if you want dual binding to work properly, you need to remember the famous sentence "Banana in a box" so you need to write [(ngModel)] it's like a banana in a box [()] .

For information, [ is for view to controller binding and ( for the inverse.

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

2 Comments

Ok, so I have changed a little bit and now it looks like: <td><input type="text" [(ngModel)]="newItem.description"></td> and created just a new object in component called newItem. Is there any way to omit the problem with Cannot read property 'description' of undefined because of the field description in newItem which has never been created?
Of course, but you will have to create a class that contains all the properties of newItem. Let's say that your class is called Item, so in your controller, you just have to instantiate an object of that class: newItem : Item = new Item();

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.