Thursday, April 26, 2018

How do I loop through ViewChildren in an Angular 4 application and affect them?

Let's say we have a bunch of tabs which are a third party component which we nest in our own component like so...

<my-tab *ngFor="let segmentTier of segmentTiers" #tabs>
</my-tab>

 
 

...and loop in at the TypeScript side like so:

@ViewChildren('tabs') tablist: QueryList<MyTabComponent>

 
 

Well, let's also say that we want to set which tab is selected based on a route parameter that is called "segment" for example. We can do that in the ngAfterViewInit lifecycle event like so:

ngAfterViewInit(): void {
   this.activatedRoute.params.subscribe(p => {
      const segment = p["segment"];
      let tabPosition = 0;
      let index = 0;
      for (let letter in SegmentationType) {
         if (letter === segment) tabPosition = index;
         index++;
      }
      if (this.tablist) {
         this.tablist.changes.subscribe(tl => {
            tl._results.forEach((t, index) => {
               const tab = <MyTabComponent>t;
               if (index === tabPosition) {
                  tab.active = true;
               } else {
                  tab.active = false;
               }
            });
            this.ref.detectChanges();
         });
      }
   });
}

Do note that there is no way to manually destroy the changes.subscribe. It will automatically clean itself up under the hood like the params.subscribe does for routing. There used to be a bug in which that didn't happen, but as of Angular 4.4.1 that has been fixed. Here are some links on as much:

No comments:

Post a Comment