我在我的其中一个按钮上放置了一个 *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/