Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Restrict Component to specific parent 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:

should be possible:

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

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

<child></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>`
});

Any ideas?

like image 555
Nicky Avatar asked Mar 09 '23 12:03

Nicky


2 Answers

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.

like image 50
n00dl3 Avatar answered Mar 12 '23 03:03

n00dl3


A slight improvement over the accepted answer lets you throw a nicer error message by using the Optional decorator and checking for null:

@Component({
  selector: 'child'
})
export class ChildComponent {
  constructor(@Optional() parent: ParentComponent){
    if (parent === null) 
      throw new Error("ChildComponent can only be used inside of ParentComponent")
  }
}
like image 40
Robin De Schepper Avatar answered Mar 12 '23 03:03

Robin De Schepper