Angular内容投影


Angular内容投影

Content Projection内容投影

内容投影用于父组件传递HTML到子组件,也就是说父组件定义子组件的HTML,传递的HTML依靠子组件的插槽确定展示的位置。

ng-content用来定义子组件的插槽,插槽分单插槽和多插槽。多插槽的使用依靠select属性,父组件可以传递多个不同内容给子组件的不同插槽。
父组件,引入子组件,在子组件tag内部定义HTML

<h1>This is parent component</h1>
<app-child>
    <header>This is header of part one</header>
    <content>this is content of part one</content>
    <footer>this is footer of part one</footer>
</app-child>
<app-child>
    <header>This is header of part two</header>
    <content>this is content of part two</content>
    <footer>this is footer of part two</footer>
</app-child>

<app-child>
    <header>This is header of part three</header>
    <content>this is content of part three</content>
    <footer>this is footer  of part three</footer>
</app-child>

子组件,定义ng-content,通过select选择传递进来的HTML

<div style="margin: 4px;">
    <h2>This is child component</h2>
    <ng-content select="header"></ng-content>
    <ng-content select="content"></ng-content>
    <ng-content select="footer"></ng-content>
</div>

显示效果,
在这里插入图片描述

ContentChild与ContentChildren

内容投影的HTML直接定义在父组件,父组件对其操作很容易。子组件可以通过ContentChild和ContentChildren和模版变量来对内容投影的HLML进行操作。

对父组件中内容投影部分添加模版变量#header

<h1>This is parent component</h1>
<app-child>
    <header #header>This is header of part one</header>
    <content>this is content of part one</content>
    <footer>this is footer of part one</footer>
</app-child>
<app-child>
    <header #header>This is header of part two</header>
    <content>this is content of part two</content>
    <footer>this is footer of part two</footer>
</app-child>

<app-child>
    <header #header>This is header of part three</header>
    <content>this is content of part three</content>
    <footer>this is footer  of part three</footer>
</app-child>

下面的代码通过ContentChild和模版变量获取header元素,操作需要在生命周期AfterContentInit后,
对元素的color设置为red。
@ContentChild的参数header不是元素header的名字,是模版变量#header中的header

export class ChildComponent implements AfterContentInit {
  @ContentChild('header') header!: ElementRef;
  constructor(private renderor: Renderer2) { }
  ngAfterContentInit(): void {
    this.renderor.setStyle(this.header.nativeElement, 'color', 'red');
  }
}

效果图
在这里插入图片描述
ViewChild与ContentChild:ViewChild不能用于内容投影,ContentChild只能用于内容投影。

ContentChild修饰符的使用

ContentChild返回的匹配到的第一个元素。

ContentChild(selector: string | Function | Type<any>, opts: { read?: any; static: boolean; }): any 

selector可以是template reference variable,也可以是component或者directive

  1. template reference variable 上文的例子
  2. component例子(未完成)
  3. directive例子(未完成)
  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值