【问题标题】:Call different functions based on *ngIf in angular 4在角度 4 中基于 *ngIf 调用不同的函数
【发布时间】:2018-08-24 06:40:21
【问题描述】:

我是 Angular 4 的新手。我正在尝试使用 Web 服务删除在 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);
         })
}

【问题讨论】:

  • 也添加打字稿代码。 usercount 在控制台中打印什么?
  • 添加了打字稿代码供您参考。 Userscount 变量保存该组中的用户数。

标签: angular function angular-ng-if


【解决方案1】:

这通常是个坏主意。

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

如果你写你所做的,你的函数将被调用 2、3、4、5、10 次,并会导致不稳定的行为。

相反,您应该根据要求删除组:如果用户点击,则导航...最好是发布所有代码并解释您的最终目标。完成后,我会修改我的答案。

编辑

根据您的评论,您应该有一个带有删除按钮的下拉菜单,这个按钮应该是这样的:

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

(根据自己的按钮代码)

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

【讨论】:

  • 你是对的。在无限循环中调用函数并使系统挂起。我已经添加了打字稿代码。
  • 您能否在问题中解释一下您的工作流程? “当我的用户[点击|更改页面| ...]时,我想[删除]然后[显示结果|重新路由] ...”
  • 根据您的建议编辑了问题
  • :D 不是我想读的。我已经知道你在使用 *ngIf。我想知道的是用户会做什么来删除组。我希望你像用户一样解释,如果你不了解 Javascript 或 Angular。这样,我可以向你解释如何实现你想做的事情。
  • 用户点击“删除组”按钮;它在下拉列表中列出了所有可用的组;用户从中选择组并单击“删除”按钮。
猜你喜欢
  • 2017-10-03
  • 1970-01-01
  • 2019-07-13
  • 2019-08-22
  • 1970-01-01
  • 1970-01-01
  • 2015-11-27
  • 2016-03-15
  • 2017-12-24
相关资源
最近更新 更多