简体   繁体   中英

Angular 4 inputs form set to null when using ngmodel

I'm starting with angular, angular 4 specifically, and I'm dealing with an error:

I'm creating a contact manager app, with two forms, one to add and other to edit contacts, and a panel displaying every contact data. The point is I pass with @Input / @Output all data from parent component (contacts.component.ts) to the child component (edit-contact.component.ts).

At the freezing point I offer my plunker you'll see two ouputs, the first one on edit action click (at the contact panel) and the second one on the "edit it!" clicking button on the edit form. As you can see the contact data object is passing correctly from parent to child.

{id: 1, name: "Sofia Mejia Gomez", id_number: "87654667X", age: "32", phone: "984613164", …} contacts.component.ts:33
{id: 1, name: "Sofia Mejia Gomez", id_number: "87654667X", age: "32", phone: "984613164", …} edit-contact.component.ts:36

Well, when I try to insert ngModel attribute on edit-contact.component.html template (commented at this freezing point) to make the form autofill with all contact data you choose on its panel, it works correctly but when I try to edit any input and click on "edit it!" button you can see an output on console with an object whose properties are set to null.

<div class="input-group main-data">
    <label for="name"></label>
    <input
      type="text" 
      class="form-control"
      name="name" 
      placeholder="Type your name..."><!--bindon-ngModel="contactToEdit.name"-->
    ...
  </div>

Please, I'll appreciate all your comments.

Here my Plunker: https://plnkr.co/edit/XQ1nswWI1gg22WtBad3O?p=preview

If you add the ngModel to the input, using two-way binding syntax [(ngModel)] , as described in the angular docs your Plunker appears to work as expected.

Ie

edit-contact.component.html
...
<div class="input-group main-data">
    <label for="name"></label>
    <input
      type="text" 
      class="form-control"
      name="name"
      placeholder="Type your name..."  
      [(ngModel)]="contactToEdit.name"><!-- << See Here -->
    <label for="id_number"></label>
    <input 
      type="text" 
      class="form-control" 
      name="id_number" 
      placeholder="Id number..." 
      [(ngModel)]="contactToEdit.id_number"><!-- << And Here -->
</div>
...

For the array values, "Word Experience" and "Education", you will have to use and *ngFor to loop through the array in order to easily access the properties.

Also note that when you reset the form with this.emptyInputs() and this.backAddContact() you are also resetting the model... So maybe do it after you have emitted the edited model to the parent.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM