<div #helloDiv>你好</div>
export class AppComponent {
@ViewChild('helloDiv') helloDivRef : ElementRef;
}
ngOnInit() {
console.log("初始化",this.helloDivRef )
this.helloDivRef .nativeElement.innerHTML = `<span>hello</span>`
}
@ViewChild 是一个选择器,用来查找要引用的DOM元素或者组件
如果想引用模板中的Angular组件 @ViewChild中,可以使用引用名,也可以使用组件类型
@ViewChild('ImageSliderComponent') imageSlider : ImageSliderComponent;
可以使用@ViewChildren,在@ViewChildren中可以使用引用名或者使用Angular 组件/指令的类型。声明类型为QueryList<?>
ngAfterViewInit(): void {
//Called after ngAfterContentInit when the component's view has been initialized. Applies to components only.
//Add 'implements AfterViewInit' to the class.
console.log("初始化ngAfterViewInit",this.imgs)
// this.imgs.forEach(item=>item.nativeElement.style.height="100px")
this.imgs.forEach(item=>{
this.rd2.setStyle(item.nativeElement,"height","100px")
})
}
不能直接操作dom 否则会给攻击者机会