I want to change style of second p by nth-child() selector or by class:
import { Component, ViewChild } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<div #container>
<p>para 1</p>
<p class="my-class">para 2</p>
<button>button 1</button>
</div>
`
})
export class AppComponent {
@ViewChild('container') myDiv;
ngAfterViewInit(){
console.log(this.myDiv.nativeElement.children);
}
}
The parent component was able to set the value of the child DOM Element. ViewChild makes it possible to access a child component and call methods or access instance variables that are available to the child. Let’s say we have a ChildComponent. Ideally, you will use @angular/cli to generate your component:
@ViewChild is a property decorator. It provides a powerful way to access child elements and properties. When we want to access child component element, form property i.e. form dirty, touched, etc, and directive in the parent component. @ViewChild is a very easy way to access the child elements.
So you can use native javascript function like getElementsByClassName after you got the component template as html element. No, ViewChild doesn't support class selector. To grab an HTML element, you can use template reference variable as shown below,
If you want to select by classes, you could use ElementRef . ElementRef will let you access the template of the component. So you can use native javascript function like getElementsByClassName after you got the component template as html element. No, ViewChild doesn't support class selector.
Following code will give you children element from view child
let children = this.myDiv.nativeElement.getElementsByTagName("p");
Please see the plunker code
https://plnkr.co/edit/yX2jIG?p=preview
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With