我想在只有用户编辑文档时传递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 、名称、符号
最佳答案
只需在添加时设置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/