简体   繁体   中英

Angular - two-way binding problem on ngFor loop

I am writing a project in Angular 10 and I don't know why but the property displayed through input is different than the same property displayed using interpolation in the ngFor loop. Those values start to be different every time I am pushing a new customSection to the customSections array.

html part:

  <div
    class="uk-margin-top"
    *ngFor="
      let customSection of resume.customSections;
      let customSectionIndex = index
    "
  >
      <input
        class="uk-input uk-form-blank uk-text-bold uk-text-lead uk-padding-remove-left"
        type="text"
        name="sectionName"
        [(ngModel)]="customSection.sectionName
        "
        (ngModelChange)="getHtmlContent()"
      />

      <span>{{ customSection.sectionName }}</span>

typescript part:

  onCustomSectionAddClick() {
    this.resume.customSections.push(new CustomSection("Untitled"));
    this.getHtmlContent();
  }

Everything is fine but when I click the button to add a new custom section then as you can see 'Untitled' is the value displayed in input for new and older (earlier added) custom sections, but span shows the other value (on this screenshot - value 'b'). Does anyone know why it can happen?

在此处输入图片说明

I did some workaround to make it work correctly, but still I know that it's just hack (not good solution):

html side:

      <input
        class="uk-input uk-form-blank uk-text-bold uk-text-lead uk-padding-remove-left"
        type="text"
        name="sectionName"
        (change)="onCustomSectionNameChange($event, customSectionIndex)"
        value="{{ customSection.sectionName }}"
      />

      <span>{{ customSection.sectionName }}</span>

typescript side:

  onCustomSectionNameChange(event: any, index: number) {
    this.resume.customSections[index].sectionName = event.target.value;
    this.getHtmlContent();
  }

After a few hours of thinking about this problem, I noticed what a simple mistake I've made. The input's name attribute should be unique in ngFor loop. So I've changed this:

  <input
    class="uk-input uk-form-blank uk-text-bold uk-text-lead uk-padding-remove-left"
    type="text"
    name="sectionName"
    [(ngModel)]="customSection.sectionName
    "
    (ngModelChange)="getHtmlContent()"
  />

to this:

  <input
    class="uk-input uk-form-blank uk-text-bold uk-text-lead uk-padding-remove-left"
    type="text"
    name="sectionName-{{ customSectionIndex }}"
    [(ngModel)]="customSection.sectionName
    "
    (ngModelChange)="getHtmlContent()"
  />

And now everything works great. Thank you guys for trying to help me and find a mistake.

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