Event when a component becomes visible

Is there a way in Angular2 to fire an event when my component becomes visible? It is placed in the tabcontrol, and I want to be notified when the user switches, I want my component to fire an event.

+6
source share
3 answers

What I finally did (which is not very pretty, but works until I have a better way to do this ...) is to use the ngAfterContentChecked() callback and handle the change itself.

 @ViewChild('map') m; private isVisible: boolean = false; ngAfterContentChecked(): void { if (this.isVisible == false && this.m.nativeElement.offsetParent != null) { console.log('isVisible switched from false to true'); this.isVisible = true; this.Refresh(); } else if (this.isVisible == true && this.m.nativeElement.offsetParent == null) { console.log('isVisible switched from true to false'); this.isVisible = false; } } 
+3
source

There is no such event, but if you use a tab control, the right way to do this is to create a @Output tab @Output for your tab control if it is executed in normal mode, otherwise most tab controls (e.g. ng-bootstrap ) also have a tab change event.

If your component needs to know about this, you can use this tab change event to determine which tab is visible, and if you know which tab is visible, you also know whether your component is visible or not. So you can do something like this:

 onTabChange(event) { this.currentTab = /** Get current tab */; } 

And then you can send it to the component itself if you have input:

 @Input() activated: boolean = false; 

And then you can apply it with:

 <my-component [activated]="currentTab == 'tabWithComponent'"></my-component> 

Now you can listen to OnChanges to see if the activated model value has changed to true .


You can also reorganize this to use the service with Observable as follows:

 @Injectable() export class TabService { observable: Observable<any>; observer; constructor() { this.observable = Observable.create(function(observer) { this.observer = observer; }); } } 

When a component wants to listen to these changes, it can subscribe to tabService.observable . When your tab changes, you can click on it with new elements using tabService.observer.next() .

+2
source

Source: https://habr.com/ru/post/1012402/


All Articles