【问题标题】:How to pass html element as child in Angular Higher Order Components (HOC)?如何在 Angular 高阶组件 (HOC) 中将 html 元素作为子元素传递?
【发布时间】:2020-09-30 23:50:16
【问题描述】:

我想在我的 Angular 高阶组件中传递一个 HTML 元素。现在我将子元素作为@Input 装饰器传递。 我的 HOC,Main Container 是这样的。

<div>
 <p> MY EXTRA UI HERE</p>
 <ng-container *ngComponentOutlet="child"></ng-container>
</div>

@Component({
  selector: 'app-main-container',
  templateUrl: './main-container.component.html',
  styleUrls: ['./main-container.component.scss'],
})
export class MainContainerComponent {
  @Input() child
}

在其他组件中,我像这样使用我的 HOC

我当前的代码:

<app-main-container [child]="child"></app-main-container>

在 .ts 文件中我像这样传递我的子组件

import { SidebarComponent } from '../sidebar/sidebar.component'
@Component({
  selector: 'app-staff',
  templateUrl: './staff.component.html',
  styleUrls: ['./staff.component.scss'],
})
export class StaffComponent {
  child: any = SidebarComponent
}

现在我想做的是,像这样的 React 格式

<app-main-container> 
    <app-staff-sidebar></app-staff-sidebar>
</app-main-container>

【问题讨论】:

    标签: javascript angular higher-order-components recompose ng-component-outlet


    【解决方案1】:

    鉴于您在问题中定义的结构

    <app-main-container> 
        <app-staff-sidebar></app-staff-sidebar>
    </app-main-container>
    

    我们可以使用ng-content 来实现这一点。

    您的main-container.component.html 应该像这样接受它:

    <div class="main-container">
      <ng-content></ng-content> <!-- This will be exchanged with the `<app-staff-sidebar></app-staff-sidebar>` that you passed in.
    </div>
    

    假设您要插入更多内容,这些内容的呈现方式与简单的让步方式略有不同,您可以使用slotsselect 关键字表示。它基本上是试图找到提供的模式。

    这样调用结构:

    <app-main-container>
      <app-staff-sidebar data-slot-type="right"></app-staff-sidebar>
      <div data-slot-type="left"></div>
    </app-main-container>
    

    并接受这样的插槽:

    <div class="main-container">
      <ng-content select="[data-slot-type=left]"></ng-content>
      <ng-content select="[data-slot-type=right]"></ng-content>
    </div>
    

    select 可以匹配任何给定的模式。它可以是 CSS 类、整个标签或 DOM 表示的任何其他内容。

    【讨论】:

    • 非常感谢 Philipp Meissner,您的解决方案运行良好?
    • 太棒了,很高兴它有帮助!如果它完全回答了您的问题,请随时接受答案:)
    猜你喜欢
    • 2018-07-28
    • 1970-01-01
    • 2019-03-16
    • 2017-08-23
    • 2019-05-02
    • 1970-01-01
    • 2012-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多