javascript - 如果满足 *ngIf 就触发函数? Angular 2

标签 javascript angular

我在我的其中一个按钮上放置了一个 *ngIf 条件,如果某些字段有效,它会显示该按钮,它会在点击时调用 geolocation() 函数。相反,我想在满足 ngIf 时自动触发此功能。我记得在 angular 1.x 中为此使用了 ng-init,但它现在似乎不起作用,*ngInit 也不起作用。

<button *ngIf="!venueNameInput.control.valid && !address1Input.control.valid" (click)="geolocation()">Test Dojo Geolocation</button>

最佳答案

使用一些组件状态实现您自己的变更检测生命周期钩子(Hook)方法:

geoCalled = false;
...
ngDoCheck() {
    if(!this.geoCalled && this.shouldCallGeo()) {
       this.geolocation();
       this.geoCalled = true;
    }
}
shouldCallGeo() {
   return !this.venueNameInput.control.valid && !this.address1Input.control.valid;
}
shouldDisplay() { return this.shouldCallGeo(); }

更新你的观点:

<button *ngIf="shouldDisplay()">Test Dojo Geolocation</button>

关于javascript - 如果满足 *ngIf 就触发函数? Angular 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34773583/

相关文章:

javascript - jQuery 使用页面滚动移动一个 div

javascript - 有什么方法可以定义执行任何计划脚本的最大持续时间?

angularjs - Grunt Typescript 找不到 Angular 核心

javascript - VS Code 强制使用分号,但 Angular TypeScript 示例的使用不一致?

javascript - 在 reactjs 应用程序中使用 dom-to-image 模块是否正确?

javascript - 引导按钮到新页面

javascript - 协助使用循环

javascript - 使用更具体的模块导入有什么好处/区别?

angular - 如何使用 Angular 5 下载文件?

angular - 如何将项目数据传递给 angular 2 的单击事件?