繁体   English   中英

用ngModel角度对话框绑定

[英]Binding with ngModel angular dialog

我有一个可以使用角度对话框进行编辑的项目,但是问题是当我打开编辑对话框时,所做的更改会自动显示在我的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));
}
}
}

您正在编辑对话框中传递原始项目的参考。 因此,即使您不保存,它也会反映出更改。 创建项目数据的副本,以使其不会与原始项目反映。 保存后,更新原始项目所需的字段。

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));
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM