【问题标题】:How component can get another component as an input?组件如何获取另一个组件作为输入?
【发布时间】:2020-04-19 05:57:18
【问题描述】:

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

@Input('name') name: string;

并在 HTML 文件中使用它:

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

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

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

【问题讨论】:

  • 您的要求是什么?从问题中不清楚您在问什么。
  • 如果你想在另一个组件中加载一个组件,你可以尝试使用ng-content
  • 输入不能使用组件,但是可以将组件放在模板中,模板可以传入输入
  • 你实际上可以通过Input绑定一个组件,但不是为了渲染它。

标签: html angular typescript angular-components


【解决方案1】:

对于在另一个组件中嵌入元素或组件,您可以像这样使用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> 

【讨论】:

    【解决方案2】:

    您不会为此使用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 的完整指南

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-06
      • 2020-10-13
      • 2023-01-12
      • 2018-12-20
      • 2021-05-09
      • 2020-01-17
      • 1970-01-01
      相关资源
      最近更新 更多