【问题标题】:Angular: wrapper component to pass inner directives/componentsAngular:用于传递内部指令/组件的包装器组件
【发布时间】:2018-08-02 02:42:52
【问题描述】:

我有 3 个组件:

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

<my-component></my-component>

(2) MyComponent:这只是一个包含TheirComponent的包装组件,像这样(my.component.html):

<their-component></their-component>

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

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

我的目标是将所有这些额外的内部指令和组件(在此示例中为their-headertheir-footer)放在 app.component.html 中,并通过 我的组件他们的组件。所以我的 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

【问题讨论】:

  • 为什么不直接导入组件呢?为什么需要以这种方式将其传递给父级?
  • @Aer0 我得把第三方组件封装起来,因为我得用这个组件写一些在我的应用中很常用的方法和参数。但是内部指令/组件对于每个用例都是唯一的,所以我不能将它们放在 my.component.html 中。
  • 您是否尝试将它们包装在 &lt;ng-container&gt; 中?
  • 只是&lt;kendo-buttongroup&gt; 不支持以任何其他方式传递按钮,而不是小时候。使用&lt;ng-content&gt; 进行投影需要以不同方式访问子项,并且对于消费组件而言,作为模板的标记看起来也不一样。
  • 看起来&lt;kendo-buttongroup&gt; 不可能,除了stackoverflow.com/questions/38888008/… 之类的东西,但我想你宁愿避免这种情况。

标签: angular typescript angular-directive angular-template


【解决方案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

另见:

【讨论】:

  • 谢谢。这正是我想要的!我最初的问题是剑道的网格,但这也适用。虽然我得到ExpressionChangedAfterItHasBeenCheckedError,但仅限于开发模式。有趣的是,ngProjectAs 没有文档。
  • Plunker 示例不再有效
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-14
  • 2018-07-28
  • 1970-01-01
  • 2018-06-24
  • 2017-05-01
  • 2017-10-11
相关资源
最近更新 更多