To show a child component (along with its ContentChildren) within the template of a parent component based on certain conditions.
app.component.html
<parent>
<child #initial>
<span>Player</span>
</child>
<child label="Intro">
<span>Intro</span>
</child>
<child label="Content">
<span>Content</span>
</child>
</tabs>
desired outcome
<parent>
<child>
<span>Player</span>
</child>
</parent>
parent.component.ts
@Component({
selector: 'parent',
template: `<!--Display {{current}} and its ContentChildren-->`,
styleUrls: ['./tabs.component.scss']
})
export class ParentComponent implements OnInit {
@ContentChildren(ChildComponent) childs;
@ContentChild("initial") initial;
@ContentChild("open") current;
ngOnInit(): void {
if (this.initial) this.current = this.initial;
}
}
child.component.ts
@Component({
selector: 'child',
template: `<ng-content></ng-content>`,
})
export class ChildComponent {
@Input() label: string;
}
Approach for parent.component.html
<ng-container *ngFor="let child in childs">
<child *ngIf="child == current"></child> //ContentChildren as defined in 'app.component.html' are lost now
</ng-container>