Angular ContentChild

contentchild

// 使用方法
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

contentchild与viewchild作用非常相似,区别在于contentchild比viewchild多了一个布局功能

比如以上代码中的p标签的内容,就显示在child-one组件的最底部

转载于:https://www.cnblogs.com/zheng-chuang/p/7418833.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值