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

问题描述 投票:2回答:1

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

@Input('name') name: string;

并在HTML文件中使用它:

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

但是我想设置component而不是字符串,例如name

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

html angular typescript angular-components
1个回答
0
投票

您不会为此使用input,您需要将内容投影与ContentChild一起使用。

示例取自Angular Docs:

@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;
}

您可以使用pane访问tab组件内的@ContentChild组件。

[C0的完整指南

© www.soinside.com 2019 - 2024. All rights reserved.