【发布时间】:2021-03-11 13:05:45
【问题描述】:
我有一些来自第三方库的组件,可以正常使用,下次使用时:
<lib>
<lib-inner [text]="'111'"></lib-inner>
<lib-inner [text]="'222'"></lib-inner>
</lib>
“lib”和“lib-inner”组件代码的简化模仿:
@Component({
selector: "lib",
template: `
<ng-container *ngFor="let c of allInner;">
<button>{{ c.text }}</button>
</ng-container>
`
})
export class LibComponent {
@ContentChildren(LibInnerComponent) allInner: QueryList<LibInnerComponent>;
}
@Component({
selector: "lib-inner",
template: ``
})
export class LibInnerComponent {
@Input() text: string;
}
我要创建包装组件:
<wrapper-for-lib>
<lib-inner [text]="'aaa'"></lib-inner>
<lib-inner [text]="'bbb'"></lib-inner>
</wrapper-for-lib>
@Component({
selector: "wrapper-for-lib",
template: `
<lib>
<ng-content></ng-content>
<lib-inner [text]="'default'"></lib-inner>
</lib>
`
})
export class WrapperForLibComponent {}
当我们使用这个 'wrapper-for-lib' 组件时,我们只能看到 'default' 按钮,但看不到按钮 'aaa' 和 'bbb'。
'lib' 组件的 ContentChildren() 找不到 ng-content 中的 'lib-inner' 组件,
有没有办法解决这个问题?
注意,我无法更改“lib”和“lib-inner”的代码,因为它们模仿了真实第三方库组件的大小写,我无法更改。
【问题讨论】:
-
尝试添加“descendants:true:
@ContentChildren(LibInnerComponent,{descendants:true}),参见文档:angular.io/api/core/ContentChildren -
谢谢,我知道这个属性,但它不适用于这种情况,我也无法更改@ContentChildren,因为它是我使用的第三方库代码的模仿.
标签: angular ng-content