Dizzy
Dizzy

Reputation: 902

Angular 2 : Is it possible to bind to 'template'?

Is it possible to have some mark-up in a variable so I can pass it into child components? For example I have three controls which are different only by error message. I would like to have only one control and pass error html or entire error component as a parameter. I could do such with text but not with html. Here is the sketch of idea:

  @Component({
      selector: 'app',
      template: `
        <template #rr>
          <div>text</div>
        </template>

        {{rr}}
      `
     })
     export class App {
     }

Expected output:

 <div>text</div>

Upvotes: 0

Views: 93

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202316

I correctly understand your question (provide some content to another component), I think that you could leverage ng-content:

@Component({
  selector: 'template',
  template: `
    <div>
      <ng-content></ng-content>
    </div>
  `
})
export class TemplateComponent {
  (...)
}

and use the component like that in the App one:

@Component({
  selector: 'app',
  template: `
    <template #rr>
      <div>text</div>
    </template>
  `,
  directives: [ TemplateComponent ]
})
export class App {
}

If you want to reference something in the ng-content within the TemplateComponent, you can leverage @ContentChild decorator (see https://angular.io/docs/ts/latest/api/core/ContentChild-var.html).

Upvotes: 3

Related Questions