-->

Angular 2 View Child / Element Ref Selecting Same

2020-07-10 09:56发布

问题:

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";
  }
  
}

Plunker

Why does my first element get colored blue and the second element does not get colored at all?

回答1:

You are using el instead el2 on your second line, which means you set background of your first div to red first, then right after to blue, but you don't do anything with your second div:

this.el.nativeElement.style.background = "red";
this.el.nativeElement.style.background = "blue";

It should be:

this.el.nativeElement.style.background = "red";
this.el2.nativeElement.style.background = "blue";