Angular 2 - Restrict Component to specific parent Component

前端 未结 1 853
走了就别回头了
走了就别回头了 2021-01-19 20:07

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 i

相关标签:
1条回答
  • 2021-01-19 20:21

    Something like that should do the trick.

    Parent component :

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

    Child component :

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

    0 讨论(0)
提交回复
热议问题