【发布时间】:2017-08-24 16:08:45
【问题描述】:
我想有条件地在父组件的模板中显示一个子组件(包括它的 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>
【问题讨论】:
-
@Vega 是的,完全正确
-
你不想使用 ngif 或 ngswitch.. ?
-
@Vega 它可以在 ngIf 中工作,但是子组件的
丢失了 -
@Vega 你到底是什么意思?
-
@Vega 我已经尝试过了,但是由于子组件的 ContentChildren 是在父组件之外定义的,因此它们必须保持动态。我在问题中添加了包装器的尝试
标签: angular typescript