5

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);
  } 
}
Badis Merabet
  • 13,970
  • 9
  • 40
  • 55
  • why dont you use `[ngClass]` ? – FAISAL Aug 09 '17 at 13:30
  • Thanks @Faisal ! I have different use case, but i think it's not possible. take a look here : https://stackoverflow.com/questions/40759325/how-to-get-dom-elements-by-class-id-selectors-and-properties . – Badis Merabet Aug 09 '17 at 14:09

1 Answers1

6

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

Rohan Fating
  • 2,135
  • 15
  • 24
  • Thank you Rohan ! – Badis Merabet Aug 09 '17 at 14:13
  • 1
    If you are using nativeElement functions, you could just use document.getElementsByTagName(). The nativeElement property is not WebWorker or Universal safe as far as I know, so add in a browser check – Drenai Jan 27 '18 at 20:56