我想在父组件的模板中有条件地显示子组件(包括其ContentChildren)。
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>
期望的结果
<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;
}
尝试使用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>
答案 0 :(得分:0)
您可以使用ngSwitch
。
<parent>
<div [ngSwitch]="current">
<child1 *ngSwitchCase="'Intro'" label="Intro">
<span>Intro</span>
</child1>
<child2 *ngSwitchCase="'Content'" label="Content">
<span>Content</span>
</child2>
</div>
</parent>
如果您不想要ngSwitch
并且需要动态更改整个模板,希望以下答案会有所帮助
here