有关内容投影的学习理解

72 阅读1分钟

基本使用

具体基本使用参照官网

单插槽内容投影:angular.cn/guide/conte…

多插槽内容投影:angular.cn/guide/conte…

ContentChild&ContentChildren

可以获取投影内容中的元素 组件 指令

注意点:

如果一个组件从未定义 ng-content 元素或者该 ng-content 元素位于 ngIf 语句内部,该内容也会被初始化

创建一个组件 content-demo,在该组件中不使用 ng-content 元素

<!-- content-demo.component.html -->
<!-- 当前组件中并未使用ng-content元素 或者 ng-content元素在一个ngIf语句里面 -->
<div></div>
<!-- <div *ngIf="show">
   <ng-content></ng-content>
</div> -->

在 app 组件中使用该组件

<!-- app.component.html -->
<!-- 在用该组件的时候,依旧提供内容,这些内容依旧会被初始化,并且在content-demo.component.ts中,依旧可以通过ContentChild或者ContentChildren获取到这些内容 -->
<app-content-demo>
  <h2 #title>this is a title</h2>
  <app-other-cpn #otherCpn></app-other-cpn>
</app-content-demo>

在 content-demo.component.ts 中通过 ContentChild 获取投影内容

// content-demo.component.ts
import { AfterViewInit, Component, ContentChild, ElementRef } from "@angular/core";

@Component({
  selector: "app-content-demo",
  templateUrl: "./content-demo.component.html",
  styleUrl: "./content-demo.component.less",
})
export class ContentDemoComponent implements AfterViewInit {
  // 通过ContentChild获取投影内容
  @ContentChild("title", { static: true }) titleEl: ElementRef | undefined;
  @ContentChild("otherCpn", { static: true }) otherCpn: OtherCpn | undefined;

  show = false;

  ngAfterViewInit(): void {
    console.log(this.titleEl);
    console.log(this.otherCpn);
  }
}