Mat
Mat

Reputation: 185

How accessing ng-content value when it's text only?

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?

Upvotes: 6

Views: 4989

Answers (1)

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24404

You just need to change the value property to textContent

ngAfterViewInit() {
    console.log('textElement', this.textElement.nativeElement.textContent);
}

Upvotes: 7

Related Questions