【问题标题】:Angular 2 - Restrict Component to specific parent ComponentAngular 2 - 将组件限制为特定的父组件
【发布时间】:2017-03-23 11:31:58
【问题描述】:

在 Angular 2 中可以将 Component 限制为页面上的特定父元素。换句话说,如果某个父元素存在,则只允许在页面上使用Component。用例:

应该可以

<parent>
  <child></child>
</parent>

应该不可能(没有&lt;parent&gt;标签作为父级)

<child></child>

我需要父 Component 进行嵌入,&lt;child&gt; 标签是可选的,所以我不能这样做:

@Component({
  /*...*/
  selector: 'parent',
  template: `<child></child>`
});

有什么想法吗?

【问题讨论】:

标签: javascript angular typescript


【解决方案1】:

类似的东西应该可以解决问题。

父组件:

@Component({
  selector: 'parent',
  template: '<ng-content></ng-content>'
})

export class ParentComponent {

}

子组件:

@Component({
  selector: 'child',
  template: ''
})
export class ChildComponent {
  constructor(parent: ParentComponent){
    // will throw a no provider error if parent is not set
  }
}

那么你就可以随意使用你的组件了:

<parent><child></child></parent> <!-- works -->
<child></child> <!-- fails -->

请注意,当您将父级注入子级时,子级实际上可以是孙子级而不会引发错误。

【讨论】:

  • 子组件仍然可以在任何地方使用
  • 不,您会收到“No provider for ParentComponent”错误。
  • 检查我的plnkr,我放了一个没有父级的&lt;child&gt;&lt;/child&gt;,并抛出异常......
  • 用于在子构造函数中将ParentComponent 标记为@Optional() 的任何地方
  • 有一种情况你的方法行不通。 &lt;parent&gt;&lt;other-parent&gt;&lt;child&gt;&lt;/child&gt;&lt;/other-parent&gt;&lt;/parent&gt; 如果孩子必须直接在父母之下,代码不会失败。看这里plnkr.co/edit/PuxtjSxyBzKTN17n7zXS
猜你喜欢
  • 2018-03-11
  • 2018-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-13
  • 1970-01-01
  • 2023-03-06
  • 2018-07-07
相关资源
最近更新 更多