First of all, let me start off with saying that I did read the docs, some articles, the ng-book chapter, etc. I still don't have a good grasp of how these things work.
With that said, consider the following:
import { Component, ViewChild, ElementRef } from '@angular/core'
@Component({
selector: 'home',
template: `
<div>Test</div>
<input type="text"#testElem>
<input type="text"#testElem2>
`
})
export class HomeComponent{
@ViewChild('testElem') el:ElementRef;
@ViewChild('testElem2') el2:ElementRef;
ngAfterViewInit() {
this.el.nativeElement.style.background = "red";
this.el.nativeElement.style.background = "blue";
}
}
Why does my first element get colored blue and the second element does not get colored at all?
You are using
el
insteadel2
on your second line, which means you setbackground
of your firstdiv
tored
first, then right after toblue
, but you don't do anything with your seconddiv
:It should be: