加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 10:16:48 所属栏目:安全 来源:网络整理
导读:首先,让我先说我已经阅读了文档,一些文章,ng-book章等等.我仍然没有很好地理解这些东西是如何工作的. 话虽如此,请考虑以下事项: import { Component,ViewChild,ElementRef } from '@angular/core'@Component({ selector: 'home',template: ` divTest/div in
首先,让我先说我已经阅读了文档,一些文章,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";
  }

}

Plunker

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

你在第二行使用el而不是el2,这意味着你先将第一个div的背景设置为红色,然后再将其设置为蓝色,但是你不会对你的第二个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";

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读