我正在尝试使用@ContentChild
获取多个模板引用,但会显示第一个。
modal.component.html
<div class="ac-modal">
<ng-container [ngTemplateOutlet]="modalHeader"></ng-container>
<ng-container [ngTemplateOutlet]="modalBody"></ng-container>
<ng-container [ngTemplateOutlet]="modalFooter"></ng-container>
</div>
modal.component.ts
@Component({
selector: 'ac-modal',
templateUrl: './modal.component.html',
styleUrls: ['./modal.component.css']
})
export class ModalComponent implements OnInit, OnDestroy, AfterContentInit {
@ContentChild(TemplateRef) modalHeader: TemplateRef<void>;
@ContentChild(TemplateRef) modalBody: TemplateRef<void>;
@ContentChild(TemplateRef) modalFooter: TemplateRef<void>;
ngAfterContentInit() {
console.log("HEADER: ", this.modalHeader);
console.log("body: ", this.modalBody);
console.log("footer: ", this.modalFooter);
}
}
app.component.html
<ac-modal>
<ac-modal-header *acModalHeader></ac-modal-header>
<ac-modal-body *acModalBody></ac-modal-body>
<ac-modal-footer *acModalFooter></ac-modal-footer>
</ac-modal>
模态-footer.directive.ts
@Directive({
selector: '[acModalFooter]'
})
export class ModalFooterDirective {
constructor(tempalteRef: TemplateRef<void>,
modalComponent: ModalComponent) {
modalComponent.modalFooter = tempalteRef;
}
}
模态-header.directive.ts
@Directive({
selector: '[acModalHeader]'
})
export class ModalFooterDirective {
constructor(tempalteRef: TemplateRef<void>,
modalComponent: ModalComponent) {
modalComponent.modalHeader = tempalteRef;
}
}
模态-body.directive.ts
@Directive({
selector: '[acModalBody]'
})
export class ModalFooterDirective {
constructor(tempalteRef: TemplateRef<void>,
modalComponent: ModalComponent) {
modalComponent.modalBody = tempalteRef;
}
}
输出
modal-header works!
modal-header works!
modal-header works!
我在modal.component.html
内<ac-modal>
组件中首先放置的标记会显示3次。 3次,因为我在<ng-container>
中有3 modal.component.html
,但我无法弄清楚为什么会发生这种情况,因为我为每个传递了不同的模板参数。
答案 0 :(得分:1)
您正在查询TemplateRef
,因此Angular将始终为您提供第一个。{您希望定位所需的特定指令:
@ContentChild(ModalHeaderDirective, {read: TemplateRef}) modalHeader: TemplateRef<void>;
@ContentChild(ModalBodyDirective, {read: TemplateRef}) modalBody: TemplateRef<void>;
@ContentChild(ModalFooterDirective, {read: TemplateRef}) modalFooter: TemplateRef<void>;
如果你这样做,你甚至不需要在指令中注入ModalComponent
,@ContentChild
足以获得TemplateRefs
。
答案 1 :(得分:0)
因为ContentChild
只获得第一个匹配选择器
将 modal.component.ts 更改为
modalHeader: TemplateRef<void>;
modalBody: TemplateRef<void>;
modalFooter: TemplateRef<void>;
@ContentChildren(TemplateRef) templateRefs;
ngAfterContentInit() {
this.templateRefs.forEach((template: TemplateRef<void>) => {
if (template === this.modalHeader) {
//here you can do stuff for ModalHeaderComponent
}
});
}