Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: How to Find Children Element in @ViewChild by CSS Selector?

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);
  } 
}
like image 724
Badis Merabet Avatar asked Aug 09 '17 13:08

Badis Merabet


People also ask

What is viewchild in Angular 2?

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:

What is the use of @viewchild in HTML?

@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.

Does viewchild support Class Selector in JavaScript?

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,

How do I select a class in a viewchild?

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.


1 Answers

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

like image 134
Rohan Fating Avatar answered Oct 19 '22 04:10

Rohan Fating