TemplateRef Content to Variable

10,816

Solution 1

Finally I found a solution corresponding to what I wanted to do:

Stackblitz sample

app.component.ts

@Component({
  selector: 'my-app',
  template: `
    <div>
      <text-ellipsis>My very very very very long text sentence</text-ellipsis>
    </div>
  `,
  styles: [`
    div {
      width:100px
    }
  `]
})
export class AppComponent  {
}

text-ellipsis.component.ts

@Component({
  selector: 'text-ellipsis',
  template: `
    <div class="text-container">
      <span [title]="text.innerText" #text><ng-content></ng-content></span>
    </div>
  `,
  styles: [`
    .text-container {
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
    }
  `]
})
export class TextEllipsisComponent {
}

In this way, I can display the text provided by the ng-content AND set it in the title attribute.

Solution 2

I don't think what you want can be made work (see comments below your question)

My suggestion is

<ng-template #text>My simple string text</ng-template>
<my-comp [text]="text"></my-comp>

and get it like

  @Input() text: TemplateRef<string>;

  ngAfterViewInit(): void {
    console.log('text', this.text);
  }

Then you can use the template reference to output it

<ng-container *ngTemplateOutlet="text"></ng-container>

StackBlitz example

Share:
10,816
JoG
Author by

JoG

Updated on August 20, 2022

Comments

  • JoG
    JoG almost 2 years

    I would like to get the innerText of the ng-content of a component as a simple string to be able to reuse it.

    I tried something like this:

    @Component({
      selector: 'my-comp',
      template: `
        <div class="text-container">
          <span class="text" [title]="text">{{text}}</span>
        </div>
        <ng-template #text>
          <ng-content></ng-content>
        </ng-template>
      `
    })
    export class MyComponent implements AfterViewInit {
      @ViewChild('text') text: TemplateRef<string>;
    
      ngAfterViewInit(): void {
        console.log(this.text);
      }
    }
    

    And I use it like this:

    <my-com>
      My simple string text
    </my-com>
    

    The goal is to get my string My simple string text into the variable text ...

    Thoughts?

  • JoG
    JoG over 6 years
    But I would like to display "My simple string text" and not the template object "[object,object]". It is exactly the same as stackblitz.com/edit/angular-abvfxy?file=app/my.component.ts but in my example, you have the benefit of removing the input parameter. I think the easiest way is to pass the real string value as an input of my component: <my-comp [text]="My simple string text"></my-comp> but I just wanted to know if it is possible to do it using transclusion...
  • Günter Zöchbauer
    Günter Zöchbauer over 6 years
    Sorry, forgot that output part. I updated the example