Home > Software engineering >  Passing label value from HTML to TS
Passing label value from HTML to TS

Time:11-11

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.

CodePudding user response:

I'm not sure if you are using any frameworks/libraries on the UI side. Just see if this code is enough

document.getElementById("ABCD").attributes.getNamedItem("label").value

CodePudding user response:

If sh-toggle is your own directive (e.g.: ToggleDirective) then you can access its properties by @ViewChild:

  1. considering you have a label @Input within ToggleDirective
  2. add @ViewChild(ToggleDirective) toggle:ToggleDirective;
  3. then simply anywhere from .ts just toggle.label

This is an angular way to access a component property.

document.getElementByID is never the angular way.

Stackblitz example

CodePudding user response:

You can use viewchild query to fetch a child component.

template:

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

js:

@ViewChild('el', { read: ElementRef }) el: ElementRef;

ngAfterViewInit(): void {
   console.log('label', this.el.nativeElement.getAttribute('label'));
}
  • Related