Event when component becomes visible

2020-06-30 04:33发布

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

4条回答
小情绪 Triste *
2楼-- · 2020-06-30 05:08

There is no such event, but if you're using a tab control, the proper way to do this would be to create a tab change @Output for your tab control if it's custom, otherwise, most tab controls (like ng-bootstrap) have some tab change event as well.

If your component has to be aware of this, you can use this tab change event to detect which tab is visible, and if you know which tab is visible, you also know if 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 your component itself if you have an 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 model value activated changed to true.


You can also refactor this to use a service with an Observable like this:

@Injectable()
export class TabService {
  observable: Observable<any>;
  observer;

  constructor() {
    this.observable = Observable.create(function(observer) {
      this.observer = observer;
    });
  }
}

When a component wishes to listen to these changes, it can subscribe to tabService.observable. When your tab changes, you can push new items to it with tabService.observer.next().

查看更多
Melony?
3楼-- · 2020-06-30 05:10

For those watching at home, you can now use ngAfterContentInit() for this, at least on Ionic anyway. https://angular.io/guide/lifecycle-hooks

查看更多
\"骚年 ilove
4楼-- · 2020-06-30 05:13
\"骚年 ilove
5楼-- · 2020-06-30 05:27

What I finally did (which is not very beautiful but works while I don't have a better way to do it...) is to use the ngAfterContentChecked() callback and handle the change myself.

@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;
    }
}
查看更多
登录 后发表回答