Search code examples
htmlangulartypescriptfilterlabel

Passing label value from HTML to TS


I have a code that goes something like this :

<sh-toggle label='ABCD' id = 'ABCD'> </sh-toggle>

I want to extract the value of label in TS file. Please tell me how it can be done? If i am trying document.getElementByID('ABCD'), then i am getting whole toggle component and unable to filter label from there.

Please mind sh-toggle is a custom tag.


Solution

  • You can use viewchild query to fetch a child component.

    Create a template reference variable(#el) for the component / element you want to query.

    <sh-toggle label='ABCD' id='ABCD' #el></sh-toggle>
    

    Use viewchild query to fetch the child component. It looks for the first element that matches the selector.

    @ViewChild('el', { read: ElementRef }) el: ElementRef;
    
    ngAfterViewInit(): void {
       console.log('label', this.el.nativeElement.getAttribute('label'));
    }