Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angular

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?

like image 335
Mat Avatar asked Apr 18 '18 07:04

Mat


People also ask

How do I get content from 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.

Can we style ng-content?

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.


1 Answers

You just need to change the value property to textContent

ngAfterViewInit() {
    console.log('textElement', this.textElement.nativeElement.textContent);
}
like image 153
Muhammed Albarmavi Avatar answered Oct 13 '22 00:10

Muhammed Albarmavi