javascript - 在 Angular 编辑时如何传递 id?

标签 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>

组件.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

最佳答案

只需在添加时设置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

关于javascript - 在 Angular 编辑时如何传递 id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48616978/

相关文章:

angularjs - 降级 Angular 2 服务时无法读取 null 的属性 'injector'

angular - 从浏览器获取 'blocked:other' 错误状态 - 在 Angular 应用程序中,我进行了一个 rest api 调用以从服务器获取信息

javascript - 如何使用 for 循环和拼接来删除单词,然后检查数组中的特定单词

javascript - Webpack 开发服务器重新加载,但页面未更改

html - 在 ngFor Angular 2 中设置输入类型复选框的选中状态

css - sass 如何与 angular4 中的 webpack 一起使用?

css - 如何修复 Angular 2 中的错误 “Could not find Angular Material core theme”?

javascript - 当弹出窗口在前面时如何突破 iFrame?

javascript - ajax.js 或 filename.js 末尾的 ver=3.1.2 是什么意思?ver=3.1.2 是什么意思?

javascript - 在隐藏的 DIV 上渲染 Chartjs