Angular 中的组件 - 投影

优质
小牛编辑
116浏览
2023-12-01

如果我们要将替换为提供给ChildComponent的任何HTML,我们应该怎么办? 一个诱人的想法是定义一个包含文本的,但如果你想提供样式化的HTML或其他组件呢? 尝试使用@Input处理这个问题可能会很快弄乱,这是内容投影的地方。组件默认情况下支持投影,您可以使用ngContent指令将投影内容放置在模板中。

因此,改变ChildComponent使用投影:

app/child/child.component.ts

  1. import { Component } from '@angular/core';
  2. @Component({
  3. selector: 'rio-child',
  4. template: `
  5. <div style="border: 1px solid blue; padding: 1rem;">
  6. <h4>Child Component</h4>
  7. <ng-content></ng-content>
  8. `
  9. })
  10. export class ChildComponent {
  11. }

app/app.component.html

这告诉Angular,对于<rio-child>的开始和结束标记之间出现的任何标记,放置在<ng-content></ng-content>内。
当这样做,我们可以有其他组件,标记等投影在这里和ChildComponent不需要知道或关心提供什么。

  1. import {Component, Input} from '@angular/core';
  2. @Component({
  3. selector: 'child',
  4. <h4>Child Component</h4>
  5. <ng-content select="header"></ng-content>
  6. <ng-content></ng-content>
  7. <ng-content select="footer"></ng-content>
  8. `
  9. })
  10. class ChildComponent {}

然后在模板中,我们可以使用指令,例如<header>,通过select =“header”指定投影内容到ng-content的位置:

app/app.component.html

除了使用指令,开发人员还可以通过css类选择 :

  1. <ng-content select=".class-select"></ng-content>

View Example