Angular 2 Preview Child / Element Ref Selects the same element twice

First of all, let me start by reading documents, some articles, the ng-book chapter, etc. I still don’t know how it works.

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 is my first element painted blue and the second element is not painted at all?

+4
source share
1 answer

Instead, you use elinstead el2on the second line, which means that first set backgroundyour first divto red, and then immediately after blue, but you will not 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";
+6

Source: https://habr.com/ru/post/1668676/


All Articles