最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Trigger function if *ngIf is satisfied? angular 2 - Stack Overflow

programmeradmin1浏览0评论

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 on validAddressAndVenue. – 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
Add a ment  | 

1 Answer 1

Reset to default 2

Implement 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>
发布评论

评论列表(0)

  1. 暂无评论