【问题标题】:Angular: *ngFor not updating view after array changesAngular:*ngFor 在数组更改后不更新视图
【发布时间】:2019-01-26 22:44:55
【问题描述】:

我正在使用 Angular 制作一个网络应用程序,但是我遇到了加载按钮的问题。因此,用户按下加载按钮,选择要加载的保存,然后将一组新属性加载到表单中,每个表单都构成步进器中的一个步骤项。加载所有表单的表单数组使用此函数“重置”:

private resetPropForms(): void {
  this.propForms = [];
}

这是接收属性事件作为参数然后设置表单数组的函数:

onPropertiesEmitted(properties: Property[]): void {
  this.resetPropForms();
  this.resetDividedProperties();
  this.resetUndividedProperties();
  this.setDividedProperties( properties );
  this.setForms();
  this.setUndividedProperties( properties );
}

这就是我的模板的样子:

<se-stepper
    *ngIf="undividedProperties"
    [linearMode]="false"
    [(activeStepIndex)]="activeStepIndex"
  >
    <se-step-item
        *ngFor="let form of propForms"
    >
        <app-properties-form
            [propertiesForm]="form"
            (change)="onPropertiesChanged($event)"
        >
        </app-properties-form>
    </se-step-item>

  </se-stepper>

最后,视图会更新,但只有在我进入下一步并返回之后。如果我保存属性,那么即使视图中显示的值不正确/未更新,也会将正确的值发送到后端。任何想法为什么会发生这种情况。我尝试将 trackBy 与每个表单的唯一标识符一起使用(使用随机数),但这不起作用。我尝试使用 ChangesRef 和 detectChanges() 并没有奏效。当我省略 *ngFor 并仅显示数组中的第一个表单时,它会正确更新,因此我相信这个问题与 *ngFor 有关。

编辑:我很确定放在 onPropertiesEmitted() 中的 setTimeout() 有效,但我忘记了我把它放在哪里使它工作,这似乎不是解决问题的好方法

【问题讨论】:

    标签: javascript angular typescript view


    【解决方案1】:

    我认为问题是数组是相同的,并且更改检测不会检测到更改,试试这个

    private resetPropForms(): void {
      //this.propForms = [];
    
      //array.slice() returns new array
      this.propForms = this.propForms.slice(0,0);
    }
    

    您还可以在分配新属性之前重置表单 (form.reset())

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-29
      • 1970-01-01
      • 2019-12-09
      • 1970-01-01
      • 2022-11-24
      • 1970-01-01
      • 1970-01-01
      • 2020-01-30
      相关资源
      最近更新 更多