0

Assuming I have a custom component that can be called as

<c-component>
  <c-title>title text</c-title>
  <c-help>help text</c-help>
</c-component>

or as just <c-component></c-component> or with either/only of the sub-compoenents. And I want to present a completely different interface for c-component if there is not a sub-component vs. if there is.... Is there way I can query the existence of a child content element without inserting it? e.g. in the c-content's template

<element if="c-help componenet exists">
  <various elements and stuff that can't go in the c-help directive/>
  <ng-content selector="c-help"></ng-content>
</element>
<element if="c-title component exists">
  <various elements and stuff that can't go in the c-help directive/>
  <ng-content selector="c-title"></ng-content>
</element>
<element if="c-title and c-help component don't exist">
  <various elements and stuff that can't go in the c-help directive/>
  <ng-content></ng-content>
</element>
micronyks
  • 54,797
  • 15
  • 112
  • 146
Robert
  • 1,024
  • 2
  • 9
  • 21

1 Answers1

0

@ContentChild() can be used for this:

@Comonent({
  ...
  template: `
  <div *ngIf="viewMode == 'simple'>
   <div>simple ui></div>
  </div>
  <div *ngIf="viewMode == 'advanced'>
   <div>advanced ui></div>
  </div>
`
})
class MyComponent {
  viewMode:string;
  @ContentChild(CTitle) cTitle:CTitle;

  ngAfterViewInit() {
   this.viewMode = this.cTitle ? 'simple' : 'advanced';
  }
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 1
    could you possibly update with an example where the subcomponent is standard native dom element? e.g. what if title were just `
    my title
    ` Could I still pick that up with contentchild decorator? - my bad for the bad example, I know I showed them both as custom components...
    – Robert Jun 10 '16 at 16:26
  • With a native DOM element you would need to add a template variable like `
    `, then you could query like `@ContentChild('cTitle') cTitle:CTitle;`. Without anything it would be a bit difficult. You could inject `ElementRef` to the wrapper element and search with `elementRef.nativeElement.querySelector(...)` but that is rather bad style.
    – Günter Zöchbauer Jun 10 '16 at 16:30
  • 1
    @Robert, another alternative (to `querySelector` or a local template variable) is a directive. But I'm not a fan of that approach. I discuss that approach here: http://stackoverflow.com/a/36900712/215945 – Mark Rajcok Jun 10 '16 at 16:45
  • I also just answered a question with a similar problem with a Plunker example http://stackoverflow.com/questions/37752328/angular-2-contentchild-apply-html-attibutes – Günter Zöchbauer Jun 10 '16 at 16:51