0

我想在我的 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>
4

1 回答 1

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>

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

像这样调用结构:

<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 表示的任何其他内容。

于 2020-06-11T11:07:26.090 回答