I have an expander that uses content projection. The expander content is wrapped into an *ngIf (for performance optimization). Unfortunately I realized that all my directives within the expandable get initialized at the very application start, even though the expandable is initially closed.
My directive must not initialize before the expandable is actually opened. So either I need some kind of initialization delay, or a hook that triggers when the directive is actually rendered.
An example code (Plunker here: https://plnkr.co/edit/R84AXZheAtZYLRmeSfkm?p=preview):
@Component({
selector: 'my-app',
template: `
<some-component>
Projected content <div some-directive></div>
</some-component>
`,
})
export class App {}
//************* Component that uses content projection *************
@Component({
selector: 'some-component',
template: `
<button (click)="showBody=!showBody">Toggle Content</button>
<div *ngIf="showBody">
<ng-content></ng-content>
</div>
`,
})
export class SomeComponent {
constructor() {}
private showBody = false;
}
//************* Directive that is set within an ng-if *************
@Directive({
selector: '[some-directive]',
})
export class SomeDirective {
constructor() {
}
ngOnInit() {
document.body.append('This should not be executed when the content is not visible');
}
}
A Plunker can be found here: https://plnkr.co/edit/R84AXZheAtZYLRmeSfkm?p=preview