Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access html elements of component tag?

Tags:

html

angular

I want to access plain HTML declared in my component tag. Suppose I have component

@Component({
  selector: 'app-demo'
  template: '<some_template></some_template>'
})
export class AppDemoComponent {

}

if I am defining h1 inside the tag in another component

<app-demo>
  <h1> demo text </h1>
</app-demo>

How can I access the h1 element inside the AppDemoComponent?

Edit: This question is not about ViewChild as ViewChild gets information from the current template of the component. I'm asking if the component tag is called in the different file and the tag has HTML elements then how to access it.

like image 875
Plochie Avatar asked Nov 01 '25 08:11

Plochie


2 Answers

Use ElementRef

You can use ElementRef to access the current component reference, allowing you to query it for nested elements.

getElementsByTagName, querySelectorAll, and getElementsByClassName will look down into the nested elements as they operate by inspecting what's rendered in the DOM, ignoring any encapsulation Angular does.

I am not sure if there is an Angular specific way to do it, but using vanilla JS lets you get there.


Child Component

import { Component, OnInit } from "@angular/core"

@Component({
    selector: 'app-demo-child'
    template: `
        <h1> demo text </h1>
        <h1 class="test"> demo text2 </h1>
        <h1> demo text3 </h1>
    `
})
export class AppChildComponent {
}

Parent Component

import { Component, OnInit, ElementRef } from "@angular/core"

@Component({
    selector: 'app-demo-parent'
    template: `
        <app-demo-child></app-demo-child>
    `
})
export class AppParentComponent {
    constructor(
        private elRef:ElementRef
    ) {  }

    doStuff() {
        let HeaderElsTag = this.elRef.nativeElement.getElementsByTagName('h1') // Array with 3 h3 elements
        let HeaderElsQuer = this.elRef.nativeElement.querySelectorAll('h1') // Array with 3 h3 elements
        let HeaderElsClass = this.elRef.nativeElement.getElementsByClassName('test') // Array with 1 h3 element
    }
}

Warning, this will look indiscriminately within your component, so be careful that you don't have nested elements with the same class name otherwise you'll have some hard to debug side effects

like image 84
David Alsh Avatar answered Nov 02 '25 22:11

David Alsh


You can use content children. for your reference please follow the link below: content children vs view children

like image 45
Nour Avatar answered Nov 02 '25 21:11

Nour