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>
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>
Share
Improve this question
edited Jan 13, 2016 at 18:45
Mark Rajcok
365k114 gold badges500 silver badges494 bronze badges
asked Jan 13, 2016 at 17:50
IljaIlja
46.6k103 gold badges289 silver badges528 bronze badges
5
-
Why not create a setter for
validAddressAndVenue
, then set a watcher on the variable? – jperezov Commented Jan 13, 2016 at 17:54 - @jperezov Could you expand on the ment, not entirely sure what you have in mind. I'm trying to figure out how to use observables for this atm, something similar? – Ilja Commented Jan 13, 2016 at 18:16
-
1
There is probably a better solution but you could always just do this:
*ngIf="!venueNameInput.control.valid && !address1Input.control.valid && (geolocation() || true)"
– rob Commented Jan 13, 2016 at 18:19 -
Setters and getters are just plain JS. Set
validAddressAndVenue
equal to!venuNameInput.control.valid && !address1InputControl.valid
, then set a watcher onvalidAddressAndVenue
. – jperezov Commented Jan 13, 2016 at 18:22 - 1 @rob this calls function many times, basically keeps repeating while statement is true. – Ilja Commented Jan 13, 2016 at 18:23
1 Answer
Reset to default 2Implement your own change detection lifecycle hook method, with some ponent 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>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745487296a4629823.html
评论列表(0条)