Skip to content

Instantly share code, notes, and snippets.

@benfoley
Created October 10, 2016 04:09
Show Gist options
  • Save benfoley/7a73f18bc54a5dc2ac92393731b31b46 to your computer and use it in GitHub Desktop.
Save benfoley/7a73f18bc54a5dc2ac92393731b31b46 to your computer and use it in GitHub Desktop.
Angular2 ViewChild ViewChildren

Access DOM elements with Angular2's ViewChild and ViewChildren. I know it's not the preferred way, but sometimes handy.

Add a #label to the element in html.

Access that in the component by setting queries in the component decorator.

Then after the view is initialised we can get the nativeElement.

ViewChildren gives us a QueryList. The children aren't accessed directly through that, but we can filter/map/foreach that to get to the elements.

<div #newCard > new card </div>
<div #existingCard *ngFor='let item of items'>
{{item}}
</div>
import { Component, ViewChild, ViewChildren } from '@angular/core';
@Component({
templateUrl: 'home.html',
queries : {
newCard : new ViewChild('newCard'),
existingCard : new ViewChildren('existingCard')
}
})
export class Home {
items: any = ['a', 'b', 'c', 'd'];
@ViewChild('newCard') newCard: any;
@ViewChildren('existingCard') existingCards: any;
constructor() {}
ngAfterViewInit() {
// get a DOM element
let target = this.newCard.nativeElement;
// This gives us Angular's QueryList object for
// the collection of DOM elements we reference via ViewChildren
console.log(this.existingCards);
// Will be called every time an item is added/removed
this.existingCards.changes.subscribe( () => console.log('Something has changed') );
// Loop through or filter/mpa/reduce to get individual elements
this.existingCards.forEach( (i) => console.log(i) );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment