使用ngModel角度对话框绑定

时间:2018-01-16 10:54:32

标签: html angular typescript

我有一个项目,我可以用对话框角度编辑,但问题是当我打开编辑对话框时,自动更改的内容会在我的UI中显示我想在保存后更改,因为如果我更改并单击取消改变。下面你可以在我注入数据并保存时找到代码。 我在对话框中更改的内容会立即覆盖更改,我保存后会发生变化。

这是打开进行编辑的对话框。

 openprojecteditdialog(project) {
 this.dialog.open(ProjectEditDialogComponent, {
  data: project, disableClose: true});
 }

这是编辑对话框的模板:

<mat-dialog-content>
<mat-tab-group>
<mat-tab label="Project">
  <div id="general-content">
    <mat-input-container>
      <label>*Name</label>
      <input placeholder="" matInput [(ngModel)]="project.name">
    </mat-input-container>
    <br>
    <mat-input-container>
      <label>*Type</label>
      <mat-select class="tab-content-item" placeholder="" matInput 
   [(ngModel)]="project.type">
        <mat-option *ngFor="let type of projectsType; let i = index" 
  [value]="i">
          {{type}}
        </mat-option>
      </mat-select>
    </mat-input-container>
    <br>
    <mat-input-container>
      <label>*State</label>
      <mat-select class="tab-content-item" placeholder="" matInput 
  [(ngModel)]="project.state">
          <mat-option *ngFor="let state of projectsState; let i 
 =index" [value]="i">
          {{state}}
        </mat-option>
      </mat-select>
    </mat-input-container>
  </div>
 </mat-tab>
 </mat-tab-group>
 </mat-dialog-content>
 <mat-dialog-actions>
  <button mat-button mat-dialog-close (click)="save()" 
 [disabled]="project.name.length === 0">Save</button>
 <button mat-button mat-dialog-close>Cancel</button>
 </mat-dialog-actions>

这是编辑对话框的TS文件。

export class ProjectEditDialogComponent implements OnInit {

readonly projectsState = ProjectState;
readonly projectsType = ProjectType;
readonly level: string[] = [];
working = false;
newType = '';
newState = '';
constructor(
public store: Store<ApplicationState>,
public dialogRef: MatDialogRef<ProjectEditDialogComponent>[],
@Inject(MAT_DIALOG_DATA) public project: any) {
}
ngOnInit() {
}
save() {
if (this.project.name.length > 0) {
  this.working = true;
  this.project.ProjectType = this.newType;
  this.project.ProjectState = this.newState;
  this.store.dispatch(new UpsertProjectInternalAction(this.project));
}
}
}

1 个答案:

答案 0 :(得分:1)

您正在编辑对话框中传递原始项目的引用。因此,即使你不节省,它也会反映出这些变化。创建项目数据的副本,使其不会反映原始项目。保存更新后,您需要原始项目的字段。

openprojecteditdialog(project) {
  let editProject = Object.assign({}, project);
  this.dialog.open(ProjectEditDialogComponent, {
  data: editProject, disableClose: true});
}

并保存功能

save() {
  if (this.editProject.name.length > 0) {
   this.working = true;
   this.project.ProjectType = this.editProject.newType;
   this.project.ProjectState = this.editProject.newState;
   this.store.dispatch(new UpsertProjectInternalAction(this.project));
  }
}