Content lifecycle on conditional transclusion
See original GitHub issueI’m submitting a …
[x] bug report
Current behavior
When you use conditional directive on <ng-content>
content component are correctly added/removed to the DOM depending on the condition but they have weird lifecycle. They have the same lifecyle than the parent, meaning when they are removed from the DOM the component instance is kept and reuse when they are added again to the DOM.
Expected behavior Content component should have their own lifecycle corresponding to the conditional. Instantiate when adding to the DOM and destroyed when removed from the DOM.
Minimal reproduction of the problem with instructions Component using transclusion like that :
@Component({
selector: 'conditional-content'
template: `
<ng-content *ngIf="condition"></ng-content>
<button (click)="condition = !condition">toggle</button>
`
})
Let’s say you do :
<conditional-content>
<some-component></some-component>
</conditional-content>
then <some-component>
will have the same lifecycle has conditional-content
.
Plunker example: https://plnkr.co/edit/KdyKG6qtiA9eoqxJOIep
What is the motivation / use case for changing the behavior?
When content component rely on ElementRef
because it becomes null when component is removed from the DOM.
-
Angular version: 2.0.X 2.X.X
-
Browser: [all]
-
Language: [all]
Issue Analytics
- State:
- Created 7 years ago
- Reactions:4
- Comments:10 (6 by maintainers)
This is by design. The lifecycle of a component is always tied to the place where the component was declared. I.e. not at the place where the
<ng-content>
is used. To conditionally create / destroy components together with content projection, use<template>
andngTemplateOutlet
.From the docs :
So from my understanding I don’t expect a component instance to exist if it’s not part of the DOM.
Any component using ElementRef on
constructor
,ngOnInit()
orngAfterViewInit()
will face a nullnativeElement
if the initial condition is false. Or even if the initial condition is true and you listen for an event, once the condition will turn to false, you won’t listen anymore to that event because the component’s element has been removed. And even if the condition becomes true again you won’t never listen to the event anymore because none ofconstructor
,ngOnInit
norngAfterViewInit()
will be called again.I took ElementRef as an example but I guess we could find more scenarios.