简体   繁体   English

使用 *ngIf,按钮在 angular 中消失

[英]using *ngIf , button disappears in angular

I am trying to add row to an existing material table using a button.我正在尝试使用按钮向现有材料表添加行。 However as I use *ngIf the button doesn't render.但是,当我使用*ngIf时,按钮不会呈现。

HTML HTML

 <button mat-raised-button color="accent" 
                           (click)="onAddRow()" 
                           *ngIf="addForm.get('rows')">Add</button>  
  

TS 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 expects a boolean value. ngIf需要一个 boolean 值。

If you pass a method, the method's stable return value will be used.如果传递一个方法,将使用该方法的稳定返回值。 If that value is not a boolean, it must be truthy for your element to be rendered.如果该值不是 boolean,则它必须是真实的,才能呈现您的元素。

If you are expecting an array of items to be returned from your method, you can use the length property as your truthy value.如果您希望从您的方法中返回一组项目,您可以使用length属性作为您的真实值。 If the array has no items, your element will not be shown.如果数组没有项目,则不会显示您的元素。

 <button mat-raised-button color="accent" 
                           (click)="onAddRow()" 
                           *ngIf="addForm.get('rows').length">Add</button> 

Your problem is not the button.你的问题不是按钮。 It is that the formArray control is created outside of your form.它是 formArray 控件是在您的表单之外创建的。 Therefore when you ask for it, nothing is returned back.因此,当您要求它时,没有任何回报。 So if the returned value is undefined the ngIf does not allow it to be visible.因此,如果返回值未定义,则 ngIf 不允许它可见。

Change your constructor as the following更改您的构造函数如下

constructor(private fb: FormBuilder) { 

    this.addForm = this.fb.group({
        project: [null ]
    });
    this.addForm.addControl("rows", new FormArray([]));
}

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

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