Plochie
Plochie

Reputation: 4117

How to access html elements of component tag?

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.

Upvotes: 4

Views: 19806

Answers (2)

Nour
Nour

Reputation: 5889

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

Upvotes: 1

David Alsh
David Alsh

Reputation: 7685

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

Upvotes: 8

Related Questions