角度2视图子/元素参考选择相同的元素两次

VSO*_*VSO 8 viewchild angular

首先,让我先说我已经阅读了文档,一些文章,ng-book章等等.我仍然没有很好地理解这些东西是如何工作的.

话虽如此,请考虑以下事项:

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

}
Run Code Online (Sandbox Code Playgroud)

Plunker

为什么我的第一个元素变成蓝色而第二个元素根本没有变色?

Ste*_*ota 12

您正在使用el,而不是el2你的第二行,这意味着你设定background的第一个divred,然后再后的权利blue,但你不与你的第二个做任何事情div:

this.el.nativeElement.style.background = "red";
this.el.nativeElement.style.background = "blue";
Run Code Online (Sandbox Code Playgroud)

它应该是:

this.el.nativeElement.style.background = "red";
this.el2.nativeElement.style.background = "blue";
Run Code Online (Sandbox Code Playgroud)