Angular 2-将组件限制为特定的父组件 [英] Angular 2 - Restrict Component to specific parent Component

查看:69
本文介绍了Angular 2-将组件限制为特定的父组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is is possible in Angular 2 to restrict a Component only to a specific parent element on a page. In other words, only allow a Component on a page if a certain parent element exists. Use case:

应该可能:

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

不应该(作为父级没有<parent>标签)

should not be possible (has no <parent> tag as a parent)

<child></child>

我需要父级Component进行转换,并且<child>标签是可选的,所以我不能

I need the parent Component to transclude and the <child> tag is optional, so I can't do:

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

有什么想法吗?

推荐答案

类似的方法应该可以解决问题.

Something like that should do the trick.

@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
  }
}

然后,您可以根据需要使用组件:

then you can use your components like you want:

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

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

Note that when you inject the parent in the child, the child can actually be the grand-child without throwing an error.

这篇关于Angular 2-将组件限制为特定的父组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆