Angular 2 View Child/Element Ref选择两次相同的元素 [英] Angular 2 View Child / Element Ref Selecting Same Element Twice

查看:184
本文介绍了Angular 2 View Child/Element Ref选择两次相同的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,让我首先说我确实阅读了文档,一些文章,ng-book章节等.我仍然对这些东西的工作原理不甚了解.

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?

推荐答案

您在第二行中使用的是el而不是el2,这意味着您将第一个divbackground设置为red首先,然后紧接着是blue,但是第二个div却不做任何事情:

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

应该是:

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

这篇关于Angular 2 View Child/Element Ref选择两次相同的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆