【问题标题】:Angular - two-way binding problem on ngFor loopAngular - ngFor循环上的双向绑定问题
【发布时间】:2020-09-14 17:59:40
【问题描述】:

我正在 Angular 10 中编写一个项目,但我不知道为什么,但是通过输入显示的属性与在 ngFor 循环中使用插值显示的相同属性不同。每次我将新的 customSection 推送到 customSections 数组时,这些值都会开始不同。

html部分:

  <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>

打字稿部分:

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

一切都很好,但是当我单击按钮添加新的自定义部分时,如您所见,“无标题”是新旧(较早添加)自定义部分的输入中显示的值,但 span 显示其他值(在此屏幕截图上 - 值“b”)。有谁知道为什么会发生这种情况?

我做了一些解决方法以使其正常工作,但我仍然知道这只是 hack(不是好的解决方案):

html端:

      <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>

打字稿方面:

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

【问题讨论】:

  • 单击按钮后您没有清除customerSection。这不会自动发生。另外,getHtmlContent() 做了什么,为什么每次更改后都要执行它?
  • @n9iels 我编辑了我的帖子以展示如何使其正常工作(hack)。 getHtmlContent() 方法只是将数据发送到 API,仅此而已
  • 我试图在 StackBlitz 上重现您的示例,但无法重现该错误。也许你没有提供什么是罪魁祸首?这里是 StackBlitz 的链接:stackblitz.com/edit/angular-ivy-kokush?file=src/app/…

标签: angular typescript


【解决方案1】:

在考虑了这个问题几个小时后,我注意到我犯了一个多么简单的错误。输入的名称属性在 ngFor 循环中应该是唯一的。所以我改变了这个:

  <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()"
  />

到这里:

  <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()"
  />

现在一切正常。谢谢你们帮助我并找出错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-20
    • 2013-09-06
    • 2017-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多