【问题标题】:How can I pass Angular directives, so they operate on child components如何传递 Angular 指令,以便它们对子组件进行操作
【发布时间】:2022-06-27 22:33:18
【问题描述】:

假设我有一个角度分量...

<MyComponent></MyComponent>

并且这个组件是这样实现的,它包含一个本机输入字段(不是通过嵌入)......

<MyComponent>
    <input>
</MyComponent>

我想将指令应用于 MyComponent,以便它真正应用于内部组件。例如:

<MyComponent mat-input></MyComponent>

我希望 matInput 指令真正应用于子组件。

如何做到这一点?

我可以将内部组件暴露为外部组件吗? 我可以在 MyComponent 上实现一些方法,以便将该指令应用于内部组件吗?

【问题讨论】:

    标签: angular angular-material


    【解决方案1】:

    实际上,您几乎没有办法将数据传递给组件。但是在所有这些中,您都必须准备要通过的内部结构。像这样:

    在你的组件 MyComponent html:

    <ng-content></ng-content>
    

    并在使用处定义传递的元素:

    <app-my-component>
      <input matInput>
    </app-my-component>
    

    --

    另一种方法是使用您的数据定义template

    <ng-template #someTemplate>
      <input matInput>
    </ng-template>
    

    然后你可以保存这个template 并作为变量操作。例如传递给您的MyComponent 并使用:

    <ng-template 
      [ngTemplateOutlet]="getTemplate(..here you should return someTemplate)">
    </ng-template>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-26
      • 2020-12-10
      • 1970-01-01
      • 2019-01-09
      • 1970-01-01
      • 1970-01-01
      • 2021-12-29
      • 2012-05-04
      相关资源
      最近更新 更多