【问题标题】:Angular Create component that depends on another higher level componentAngular 创建依赖于另一个更高级别组件的组件
【发布时间】:2020-04-27 03:31:50
【问题描述】:

我想创建除非包装在另一个更高级别的组件中否则无法呈现的角度组件。 为了更好地理解这一点,这里有一个例子(例子来自angular material标签结构):

<mat-tab-group>
    <mat-tab></mat-tab>
</mat-tab-group>

我想创建相同的结构,其中mat-tab 将是我的组件,没有mat-tab-group 包装组件就无法呈现。

我正在查看 Angular 文档,但找不到相关信息。 有人可以帮忙吗?

谢谢!

【问题讨论】:

标签: angular components


【解决方案1】:

您可以使用 Optional 和 Host 来获取“mat-tab-group”

在你的孩子身上

get hasParent()
{
    return this.hello!=null
}
constructor(@Optional() @Host() private hello:HelloComponent){}

可以在 child.component.ts 中使用

<ng-container *ngIf="hasParent">
....
</ng-container>

如果你公开打招呼,你可以在 .html(*) 中使用

<h1 *ngIf="hasParent">Hello!, parent's name is {{hello.name}}</h1>

(*)如果是私有的,您可以使用this.hello.oneProperty 或this.hello.oneFunction() 访问子级的所有公共属性 见simple stackblitz

【讨论】:

    【解决方案2】:

    感谢@Syed 正是我想要的。

    Angular 2 - Restrict Component to specific parent Component

    谢谢!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-15
      • 2015-06-01
      • 2016-07-18
      • 1970-01-01
      • 2018-07-02
      • 1970-01-01
      • 2017-02-19
      相关资源
      最近更新 更多