使用 *ngIf ,按钮在 angular 中消失
using *ngIf , button disappears in angular
我正在尝试使用按钮向现有 material table 添加行。但是,当我使用 *ngIf
时,按钮不会呈现。
HTML
<button mat-raised-button color="accent"
(click)="onAddRow()"
*ngIf="addForm.get('rows')">Add</button>
TS
constructor(private fb: FormBuilder) {
this.addForm = this.fb.group({
project: [null ]
});
this.rows = this.fb.array([]);
}
onAddRow() {
this.rows.push(this.createItemFormGroup());
}
createItemFormGroup(): FormGroup {
return this.fb.group({
name: " ",
description: "some description",
qty: null
});
}
ngIf
需要一个布尔值。
如果您传递一个方法,将使用该方法的稳定 return 值。如果该值不是布尔值,则它必须为真值才能呈现您的元素。
如果您希望从您的方法中 return 编辑一组项目,您可以使用 length
属性 作为真值。如果数组没有项目,您的元素将不会显示。
<button mat-raised-button color="accent"
(click)="onAddRow()"
*ngIf="addForm.get('rows').length">Add</button>
你的问题不在于按钮。 formArray 控件是在您的窗体之外创建的。因此,当您请求它时,不会返回任何内容。因此,如果返回值未定义,则 ngIf 不允许它可见。
按以下方式更改您的构造函数
constructor(private fb: FormBuilder) {
this.addForm = this.fb.group({
project: [null ]
});
this.addForm.addControl("rows", new FormArray([]));
}
我正在尝试使用按钮向现有 material table 添加行。但是,当我使用 *ngIf
时,按钮不会呈现。
HTML
<button mat-raised-button color="accent"
(click)="onAddRow()"
*ngIf="addForm.get('rows')">Add</button>
TS
constructor(private fb: FormBuilder) {
this.addForm = this.fb.group({
project: [null ]
});
this.rows = this.fb.array([]);
}
onAddRow() {
this.rows.push(this.createItemFormGroup());
}
createItemFormGroup(): FormGroup {
return this.fb.group({
name: " ",
description: "some description",
qty: null
});
}
ngIf
需要一个布尔值。
如果您传递一个方法,将使用该方法的稳定 return 值。如果该值不是布尔值,则它必须为真值才能呈现您的元素。
如果您希望从您的方法中 return 编辑一组项目,您可以使用 length
属性 作为真值。如果数组没有项目,您的元素将不会显示。
<button mat-raised-button color="accent"
(click)="onAddRow()"
*ngIf="addForm.get('rows').length">Add</button>
你的问题不在于按钮。 formArray 控件是在您的窗体之外创建的。因此,当您请求它时,不会返回任何内容。因此,如果返回值未定义,则 ngIf 不允许它可见。
按以下方式更改您的构造函数
constructor(private fb: FormBuilder) {
this.addForm = this.fb.group({
project: [null ]
});
this.addForm.addControl("rows", new FormArray([]));
}