首页 > 解决方案 > Angular 动态表单未按预期更新

问题描述

我有一个名为 xform 的通用表单组件

xform.component.html

<ng-template [ngIf]="src && src.cols">
    <div fxLayout="row" *ngFor="let r of src.data|jag:src">
        <div fxFlex *ngFor="let c of r">
            <el [src]="c"></el>
        </div>
    </div>
</ng-template>

XformComponent.ts

export class XformComponent implements OnInit {
  @Input() src: any;
}

这是我的锯齿管:

export class JagPipe implements PipeTransform {
  transform(data: any[], src: any): any {
    if (!data || !src) return [];
    if (!src.cols) src.cols = 2;
    var matrix = [], i, k;
    var els = data.filter(x => !x.hide);
    for (i = 0, k = -1; i < els.length; i++) {
      if (i % src.cols === 0) {
        k++;
        matrix[k] = [];
      }
      matrix[k].push(src.data[i]);
    }
    return matrix;
  }
}

el.component.html

<div fxLayout="row" *ngIf="src">
    <div fxFlex="100" [ngSwitch]="src.type">
        <mat-form-field> 
            <ng-template [ngSwitchCase]="eltype.select">
                <mat-select [(ngModel)]="src.value">
                    <mat-option *ngFor="let x of src.obs | async" [value]="x.value">
                        {{x.text}}
                    </mat-option>
                </mat-select>
            </ng-template>
                <!-- other controls like datepicker,autocomplete etc -->            
            <input matInput placeholder="{{src.title}}" *ngSwitchDefault [(ngModel)]="src.value">
        </mat-form-field>
    </div>
</div>

ElComponent.ts

export class ElComponent implements OnInit {
  @Input() src:any;
  eltype=eltype;
}

我想像下面这样使用我的 xform。

<xform [src]="arrayData">

我希望它会UI/form针对我的模型中的任何更改进行更新。

它在第一次加载时工作并显示表单。但是,如果我更改隐藏标志或从数组中删除一个项目 UI 不会按预期更新。

我尝试pure:false了管道,但它进入了无限循环。我也尝试调用一个函数ngFor,它进入无限循环。

标签: javascriptangulartypescriptangular8

解决方案


推荐阅读