// 使用方法 git clone https://git.oschina.net/mumu-osc/learn-component.git cd learn-component git pull origin contentchild npm install ng serve
<!-- test-content-child.component.html --> <div class="panel panel-primary"> <div class="panel-heading">父組件</div> <div class="panel-body"> <child-one> <h3>投影的標題</h3> <p>投影的底部</p> <child-two></child-two> <child-two></child-two> <child-two></child-two> <child-two></child-two> <child-two></child-two> <child-two></child-two> <child-two></child-two> <child-two></child-two> </child-one> </div> </div>
<!-- child-one.component.html --> <div class="panel panel-primary"> <div class="panel-heading"> <ng-content select="h3"></ng-content> </div> <div class="panel-body"> <ng-content select="child-two"></ng-content> </div> <div class="panel-footer"> <ng-content select="p"></ng-content> </div> </div>
// child-one.component.ts import { Component, ContentChild, ContentChildren, ElementRef, OnInit, QueryList } from '@angular/core'; import { ChildTwoComponent } from '../child-two/child-two.component'; @Component({ selector: 'child-one', templateUrl: './child-one.component.html', styleUrls: ['./child-one.component.scss'] }) export class ChildOneComponent implements OnInit { // @ContentChild(ChildTwoComponent) // childTwo:ChildTwoComponent; @ContentChildren(ChildTwoComponent) childrenTwo:QueryList<ChildTwoComponent>; constructor() { } ngOnInit() { } ngAfterContentInit():void{ // console.log(this.childTwo); this.childrenTwo.forEach((item)=>{ console.log(item); }); } }
contentchild與viewchild做用很是類似,區別在於contentchild比viewchild多了一個佈局功能css
好比以上代碼中的p標籤的內容,就顯示在child-one組件的最底部html