根据角度4中的* ngIf调用不同的函数

时间:2018-08-24 06:40:22

标签: angular function angular-ng-if ngif

我是Angular 4的新手。我试图删除使用Webservice在DB中创建的组。如果该组拥有任何用户,那么我必须向用户发出警告消息。如果该组为空,则可以将其删除。 对于警告消息,我使用了引导程序模态,并删除了具有Angular函数( deleteGroup(group))的功能,该函数将依次调用Web服务以删除该组。

基于该组中的用户数,我尝试使用* ngIf,但失败了。有人可以帮我解决吗?

功能流程:

1) Groups are listed in drop-down and the user chooses the one
2)Clicking on delete button, calls the getUsers() funtion to check
the availability of users in that group (group members count is
assidgned to usersCount variable )
3) Based on the usersCount, next step has to be done
   a) usersCount == 0 , => delete the group   
   b) usersCount !=0 , => pop-up warning message

HTML代码

<button type="button" class="btn btn-primary" 
     (click)="getUsers(optionSelected)" >Delete</button> //getuser function gets  the number of users in that group
     <div *ngIf="usersCount ==0 ">deleteGroup(optionSelected)</div> //usercount -> number of users
</button>

打字稿代码:

getUsers(value): void {
    this.output = [];
    this.textValue.getUsers(value)
        .subscribe(res => {
                this.output = res;
                this.usersCount = this.output.length;
                console.log ("Number of users:", this.usersCount);
         })
}

1 个答案:

答案 0 :(得分:1)

通常这是一个坏主意。

HTML模板在应用程序生命周期中被解析和检查了好几次。

如果您编写了所做的内容,则函数将被调用2、3、4、5、10次,这将导致行为不稳定。

相反,您应该应要求删除:如果用户单击,请导航……最好是发布所有代码并解释最终目标。完成后,我将对答案进行编辑。

编辑

从您的评论中,您应该具有一个带有删除按钮的下拉菜单,并且该按钮应如下所示:

<button *ngIf="!usercount" (click)="deleteGroup(optionSelected)">Delete group</button>

(根据您自己的按钮的代码)

现在,用户只需单击此按钮,就会调用该功能,删除用户组。如果用户计数为假(在您的情况下为“等于零”),则该按钮将不会显示,这意味着用户无法单击它。