Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger function if *ngIf is satisfied? angular 2

I'm placing an *ngIf condition on one of my buttons that gets displayed if certain fields validate, it calls the geolocation() function on click. Instead I want to automatically trigger this function as soon as ngIf is satisfied. I remember using ng-init for this with angular 1.x, but it doesn't seem to work now nor does *ngInit.

<button *ngIf="!venueNameInput.control.valid && !address1Input.control.valid" (click)="geolocation()">Test Dojo Geolocation</button>
like image 814
Ilja Avatar asked Oct 30 '22 11:10

Ilja


1 Answers

Implement your own change detection lifecycle hook method, with some component state:

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(); }

Update your view:

<button *ngIf="shouldDisplay()">Test Dojo Geolocation</button>
like image 159
Mark Rajcok Avatar answered Nov 12 '22 19:11

Mark Rajcok