ngFor循环

时间:2018-06-14 03:39:33

标签: angular angular-material mean

我正在尝试创建一个角度对话框,该对话框将根据给定对象的键动态创建输入。我的主要问题是绑定[(ngModel)],最后它应该像[(ngModel)] =“data.id”。

对话框html:

<h1 mat-dialog-title>Add Customer </h1>
<div mat-dialog-content>

  <mat-form-field *ngFor="let item of myKeys; let index = index; trackBy:index;" >
    <input matInput
      type="string"
      name={{item}}
      placeholder={{item}}
      [(ngModel)]="data.item"  
      >
  </mat-form-field>

</div>

You chose: <i>{{data.name}}</i>

<div mat-dialog-actions>
  <button mat-button (click)="onNoClick()">No Thanks</button>
  <button mat-button [mat-dialog-close]="data" cdkFocusInitial>Ok</button>
</div>e

对话框角度分量ts:

@Component({
  selector: 'app-dialog-edit',
  templateUrl: './dialog-edit.component.html',
})
export class DialogBoxEditComponent {
  test = [
    'data.id',
    'data.name',
    'data.address',
    'data.city',
    'data.payment'
  ];

  myKeys = this.getMyKeys(this.data);

  @Output() editMode = new EventEmitter();

  constructor(
    public dialogRef: MatDialogRef<DialogBoxEditComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any) {}

  onNoClick(): void {
    this.dialogRef.close();
  }
  getMyKeys(myData) {
    return Object.keys(myData);
  }
  getType(myIn) {
    return typeof(myIn);
  }
  getty(mytest) {
    return 'data.' + mytest;
  }
}

我尝试了什么:

[(ngModel)] =“data.item”导致所有输入共享data.id作为一个ngModel

[(ngModel)] =“test [index]”这里我尝试在组件中创建一个返回所需绑定的数组,但是这会将测试数组值填入输入字段,但是没有绑定< / p>

[(ngModel)] =“test.item”这里的test是一个对象而不是数组。这也导致第一个例子的单一共享绑定链接。 (见下图)

dialog with shared binding

任何事情都会受到赞赏。

1 个答案:

答案 0 :(得分:0)

<mat-form-field *ngFor="let item of myKeys; let index = index; trackBy:index;" >
  <input matInput type="string"
    name={{item}} placeholder={{item}}
    value = {{ data[item] }} #foo>
</mat-form-field>

在输入中添加#foo,这会将#foo绑定到每个元素,并且您的ng模型不会共享。...