Search code examples
angulartypescriptangular-templateviewchild

How to get the value of the innerHTML of a viewChild in Angular?


I need the value of a viewChild in Angular in order to check if it is an empty string or not.

My ViewChild looks like this:

@ViewChild('myItem', { static: true }) myItem: ElementRef;

I get the value like this:

console.log('itemType', this.myItem.nativeElement.firstChild); // returns "TESTSTRING"

In the console the value looks like this: "TESTSTRING" which is a string, but if I check with typeof it says that it is an object:

console.log('itemType', typeof this.myItem.nativeElement.firstChild); // returns object

I'd like to check it like this:

this.myItemIsEmpty = this.myItem.nativeElement.firstChild === ''; // returns always false

What am I doing wrong here?


Solution

  • The following part this.myItem.nativeElement.firstChild returns an element of type ChildNode - which represents a DOM element. To get the text of that, you need to use the textContent property.

    @Component({/* ...*/})
    export class MyComponent implements AfterViewInit {
       @ViewChild('myItem', { static: true }) myItem: ElementRef;
    
       // Only try to access @ViewChild/@ContentChild in/after AfterViewInit as DOM might not be rendered otherwise
       public ngAfterViewInit():void {
          this.myItemIsEmpty = this.myItem.nativeElement.firstChild.textContent === '';
       }
    }