Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
780 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...