0

MyComponent for example:

<div [my-component]="'text'"></div>

In code I have this.viewContainerRef which is the node itself (<div>).

But the user may want to add its template to myComponent, so he will do this:

<div [my-component]="'text'">
   <template>
   ...
   </template>
</div>

My question is how in code I can check if there is a <template> node and use/read its innerHTML?

AngularOne
  • 2,760
  • 6
  • 32
  • 46

1 Answers1

4

You can use ContentChild(TemplateRef) and after that render when template is defined and when it is just html. Here is an example. This is for Angular 2. For Angular 4 '*ngIf;else Block' can be used.

  @Component({
    selector: '[my-component]',
    template: `
      my-component with input {{v}}
      <ng-container *ngIf="tpl">
        Template block:
        <ng-container [ngTemplateOutlet]="tpl"></ng-container>
      </ng-container>

      <ng-container *ngIf="!tpl">
        No Template block: <ng-content></ng-content>
      </ng-container>
    `
  })
  export class MyComponent {
    @Input('my-component') v : string;
    @ContentChild(TemplateRef) public tpl: TemplateRef;
  }
  @Component({
    selector: 'my-app',
    template: `
      <div>
        <div [my-component]="'text'">
          <template><pre>hi there</pre></template>
        </div>
        <hr>
        <div [my-component]="'text1'">
          aaa
        </div>
      </div>
    `,
  })
  export class App {
    constructor() {
    }
  }
Julia Passynkova
  • 17,256
  • 6
  • 33
  • 32
  • works and simple to understand and also to use, from a user perspective that is going to use this component. Thank you! – AngularOne May 05 '17 at 14:21