Angular 5,在数组中添加新行并保存

时间:2018-08-02 07:10:06

标签: javascript arrays angular object angular5

我有这样的数组:

dataTest = [{name: 'Foo'},{name: 'Bar'}]

我正在显示matIntput中的所有数据。单击时,我将在数组中添加新行并显示空输入。没关系,但是当我将数据更改为新行而将null更改为类似于John之类的内容,然后单击“保存”时,数组中没有任何更改,看起来像这样:

dataTest = [{name: 'Foo'},{name: 'Bar'},{name: null}]

这是我的app.compoent.html:

<mat-dialog-content>
  <div class="flex wrap vertical-align" *ngFor="let profile of dataTest; let i = index">
    <mat-form-field class="profile-name name">
        <input matInput placeholder="Name" value="{{profile.name}}">
    </mat-form-field>
    <div class="action-group">
        <span class="add-button"(click)="add()">ADD</span>
    </div>
  </div>
</mat-dialog-content>
<mat-dialog-actions align="end">
  <button class="background-white" mat-button mat-dialog-close>CANCEL</button>
  <button class="background-primary" mat-button [mat-dialog-close]="true" cdkFocusInitial (click)="save(dataTest)">SAVE</button>
</mat-dialog-actions>

这是我的app.compoent.ts:

private add(): void {
 const rules: any = {
    name: ''
 };
 this.dataTest.push(rules);
 console.log(this.dataTest);
};


private save(dataTest) {
 console.log(dataTest)
}

任何帮助或想法,我做错了!

1 个答案:

答案 0 :(得分:2)

使用ngModel如下:-

{
  "error": {
    "message": "Callback must be a function"
  }
} 

如果尚未导入FormsModule,请不要忘记导入它。