首先,让我先说我已经阅读了文档,一些文章,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"; } }
为什么我的第一个元素变成蓝色而第二个元素根本没有变色?
你在第二行使用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";
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。