Angular Mat Dialog提交后返回空值""问题求助
Angular Mat Dialog 数据绑定修复方案
问题描述
输入数字并点击添加按钮后,弹出Mat Dialog对话框,在对话框中输入动物名称,提交后得到的结果为"";但通过this.data.totalCount初始化数组时功能正常,需修复该问题。
问题根因
对话框模板未实现输入框与animals数组的双向绑定,用户输入的内容无法同步到数组中,导致提交时返回的仍是初始的空字符串数组。
修复步骤
1. 修正对话框模板的双向绑定
修改dialog-overview-example-dialog.html,将输入框与数组元素绑定:
<h1 mat-dialog-title>添加动物</h1> <div mat-dialog-content> <div *ngFor="let animal of animals; let i = index"> <mat-form-field> <input matInput [(ngModel)]="animals[i]" placeholder="动物名称"> </mat-form-field> </div> </div> <div mat-dialog-actions> <button mat-button (click)="onNoClick()">提交</button> <button mat-button (click)="dialogRef.close()">取消</button> </div>
注意:需在模块中导入FormsModule(在app.module.ts中添加import { FormsModule } from '@angular/forms';并加入imports数组),否则[(ngModel)]无法生效。
2. 确认组件逻辑
对话框组件的提交方法已正确传递数组,无需修改:
onNoClick(): void { this.dialogRef.close(this.animals); }
3. 主组件接收逻辑验证
主组件的afterClosed订阅逻辑正常,会接收返回的数组并赋值:
dialogRef.afterClosed().subscribe(result => { console.log('The dialog was closed'); this.animals = result; console.log(result) });
内容的提问来源于stack exchange,提问作者Mitch
相关产品推荐
相关产品推荐

