Angular:传递内部指令/组件的包装器组件

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

我有3个组件:

(1)AppComponent:这只是一个普通的AppComponent,没什么特别的。在app.component.html中我使用myComponent:

<my-component></my-component>

(2)MyComponent:这只是一个包含ItsComponent的包装器组件(my.component.html):

<their-component></their-component>

(3)他们的组件:这是第三方组件(来自NPM包)。它可以包含来自第三方组件的指令和其他组件。例如:

<their-component>
    <their-header>Title</their-header>
    <their-footer>Title</their-footer>
</their-component>

我的目标是将所有这些额外的内部指令和组件(在此示例中为their-headertheir-footer)放在app.component.html中,并将其通过MyComponent传递给ItsComponent。所以我的app.component.html应该是这样的:

<my-component>
    <their-header>Title</their-header>
    <their-footer>Title</their-footer>
</my-component>

我尝试使用ng-content。我知道,它适用于简单的HTML元素,但不适用于这些第三方指令。这是我尝试过的(my.component.html):

<their-component>
    <ng-content></ng-content>
</their-component>

它不起作用,并且没有错误。也许这是一个内容投影问题,我不确定,这是怎么称呼的。对此有何解决方案?谢谢。


示例:https://plnkr.co/edit/SgM4sbYQrZXDcrKuon2d?p=preview

angular typescript angular-directive angular-template
1个回答
1
投票

如果你真的需要它,你可以利用ngProjectAs属性。

为了获得ButtonGroupk-group-startk-group-end类等)提供的所有附加功能,您必须将按钮数组传递给kendo组件。

这是它的样子:

import { Component, QueryList, ContentChildren, Input, ViewChild } from '@angular/core';
import { Button, ButtonGroup } from '@progress/kendo-angular-buttons';

@Component({
  selector: 'my-component',
  template: `
    <kendo-buttongroup>
        <ng-content ngProjectAs="[kendoButton]"></ng-content>
    </kendo-buttongroup>
  `
})
export class MyComponent {

  @ViewChild(ButtonGroup) buttonGroup: ButtonGroup;

  @ContentChildren(Button) buttons: QueryList<Button>;

  ngAfterViewInit() {
    this.buttonGroup.buttons = this.buttons;
    this.buttonGroup.ngAfterContentInit();
  }
}

Plunker Example

也可以看看:

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