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?
Finally I found a solution corresponding to what I wanted to do:
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.