组件如何获取另一个组件作为输入?

How component can get another component as an input?

我可以设置stringnumber作为组件的输入:

@Input('name') name: string;

并在 HTML 文件中使用它:

<div>{{name}}</div>

但我想设置一个 组件 而不是字符串,例如 name

换句话说:如何为另一个组件的输入设置一个组件

您不会为此使用 input,您需要使用 ContentChild 的内容投影。

示例取自 Angular 文档:

@Component({
  selector: 'example-app',
  template: `
    <tab>
      <pane id="1" *ngIf="shouldShow"></pane>
      <pane id="2" *ngIf="!shouldShow"></pane>
    </tab>

    <button (click)="toggle()">Toggle</button>
  `,
})
export class ContentChildComp {
  shouldShow = true;

  toggle() { this.shouldShow = !this.shouldShow; }
}

pane 分量,投影在 tabs 分量中。

@Component({
  selector: 'tab',
  template: `
    <div>pane: {{pane?.id}}</div>
  `
})
export class Tab {
  @ContentChild(Pane, {static: false}) pane !: Pane;
}

您可以使用 @ContentChild.

访问 tab 组件中的 pane 组件

关于 content projection

的完整指南

要将元素或组件嵌入到另一个组件中,您可以像这样使用 ng-content

@Component({
  selector: 'outer-CMP',
  template: `
    <div> </div>
    <ng-content></ng-content>
  `,
  styleUrls: [....]
})
export class OuterInputComponent {

}

然后 :

@Component({
  selector: 'inner-CMP',
  template: `
    <div> </div>

  `,
  styleUrls: [....]
})
export class InnerInputComponent {

}

使用:

<outer-CMP> 
        <inner-CMP>
        </inner-CMP>
</outer-CMP>