Angular 2 View Child / Element Ref Selecting Same Element Twice

拈花ヽ惹草 提交于 2019-12-21 09:36:32

问题


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


来源:https://stackoverflow.com/questions/42013071/angular-2-view-child-element-ref-selecting-same-element-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!