如何在角度编辑时传递id?

时间:2018-02-05 06:32:28

标签: javascript angular

我想在只有用户编辑文档时传递id。这是我的html和component.ts

HTML

<h1 mat-dialog-title>Hi {{data.name}}</h1>
<form  [formGroup]="addTaskForm"  (ngSubmit)="save()" >
<mat-form-field>
  <mat-select formControlName="name" placeholder="Element Name">
    <mat-option *ngFor="let element of Elements" [value]="element.name">
      {{ element.name }}
    </mat-option>
  </mat-select>
</mat-form-field>
<mat-form-field>
  <mat-select  formControlName="symbol"  placeholder="Element symbol">
    <mat-option *ngFor="let element of Elements" [value]="element.symbol">
      {{ element.symbol }}
    </mat-option>
  </mat-select>
</mat-form-field>

<div mat-dialog-actions>

  <button type="button" mat-button (click)="onNoClick()">Cancel</button>
<button type="submit"  mat-button cdkFocusInitial>Add</button>



</div>
</form>

component.ts

export class DialogOverviewExampleDialog {
 Elements = ELEMENT_DATA; 
addTaskForm: FormGroup;
  symbol = new FormControl('', Validators.required);
  name = new FormControl('', Validators.required);
  id = new FormControl('', Validators.required);
  constructor(
    public dialogRef: MatDialogRef<DialogOverviewExampleDialog>,
    @Inject(MAT_DIALOG_DATA) public data: any,
    private formBuilder: FormBuilder) { 
    if(data.element){
      console.log(data.element.name);
     this.name = data.element.name;
     this.symbol = data.element.symbol;
     this.id = data.element.id;
    }
     this.addTaskForm = this.formBuilder.group({
      name: this.name,
      symbol: this.symbol,
      id: this.id
    });
    }

  onNoClick(): void {
    this.dialogRef.close();
  }
  save(Element) {

    console.log('working');
    console.log(this.addTaskForm.value);
  }
}

当用户点击添加弹出窗口时会打开两个下拉列表并添加一个按钮,那时我不想要id,但是当用户点击编辑按钮弹出窗口时会打开特定的行详细信息,如果用户点击添加按钮,我应该得到特定的id,名称,组件中的符号

demo

1 个答案:

答案 0 :(得分:0)

添加

时,只需设置 id: this.id 即可
  this.addTaskForm = this.formBuilder.group({
      name: this.name,
      symbol: this.symbol,
      id: this.id
    });

也会使用你的模态传递id

if(data.element){
 console.log(data.element.name);
 this.name = data.element.name;
 this.symbol = data.element.symbol;
 this.id = data.element.id;
}

<强> DEMO