Angular中使用@ViewChild获取DOM节点时报错Expected 2 arguments, but got 1.
#
html代码是这样的
<div #myBox>
这是一个DOM节点
</div>
ts代码是
import { Component, OnInit ,ViewChild,ElementRef} from '@angular/core';
@Component({
selector: 'app-news',
templateUrl: './news.component.html',
styleUrls: ['./news.component.css']
})
export class NewsComponent implements OnInit {
@ViewChild("myBox") mybox: ElementRef;
constructor() { }
ngOnInit() {
}
ngAfterViewInit(): void {
this.mybox.nativeElement.style.width = "200px";
this.mybox.nativeElement.style.height = "200px";
this.mybox.nativeElement.style.background = "pink";
}
}
运行就会报错
原因是在Angular8中ViewChild还需要设置一个参数
这样写就可以正常运行啦
import { Component, OnInit ,ViewChild,ElementRef} from '@angular/core';
@Component({
selector: 'app-news',
templateUrl: './news.component.html',
styleUrls: ['./news.component.css']
})
export class NewsComponent implements OnInit {
**@ViewChild("myBox", {static: false}) mybox: ElementRef;**
constructor() { }
ngOnInit() {
}
ngAfterViewInit(): void {
this.mybox.nativeElement.style.width = "200px";
this.mybox.nativeElement.style.height = "200px";
this.mybox.nativeElement.style.background = "pink";
}
}