I'm trying to access the value of a span which value is given by ng-content.
I've got a button component containing this html in the template:
<span #text class="o-button-label">
<ng-content></ng-content>
</span>
so I can have
<my-button>Hello</my-button>
turning into
<span #text class="o-button-label">
Hello
</span>
Now I want to get that text to be able to use it as well in an aria-label.
Among other things, I tried the following in my-button component:
@ViewChild('text') textElement: ElementRef;
ngAfterViewInit() {
console.log('textElement', this.textElement.nativeElement.value);
}
But that always give me undefined. Replacing value by nodeValue returns null. I checked this.textElement.nativeElement which is the span as expected, the span contains its value as expected, but I can't find a way to get that text value.
All the search I did points to the use of @ViewChild as I did, but it's always to get some components or DOM nodes (like in this good topic), not text only, so is it even possible to get text value injected by ng-content?
Once you project content into App Component using ng-content. Now, using the template reference variable “#contentParagraph” you can access ng-content using @ContentChild within Angular component (ItemElementComponent) class as shown below.
Use the :host /deep/ selector. If you want to use the shadow DOM polyfill and style your components using the style or styleUrls attribute of the Component decorator, select the element with :host , then ignore the shadow DOM polyfill with the /deep/ child selector. :host will select the element.
You just need to change the value property to textContent
ngAfterViewInit() {
console.log('textElement', this.textElement.nativeElement.textContent);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With