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
- template reference variable 上文的例子
- component例子(未完成)
- directive例子(未完成)