多个[ngTemplateOutlet]也仅为其他人显示第一个

时间:2018-06-10 22:29:50

标签: angular angular5

我正在尝试使用@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,但我无法弄清楚为什么会发生这种情况,因为我为每个传递了不同的模板参数。

2 个答案:

答案 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
    }

});

}