angular 获取DOM元素 多种方式


第一种方式 ---ViewChild
#box>我是div----添加在html页面中

@ViewChild('box') box: ElementRef;
constructor(){
//添加在ts文件中 该方法不可放在constructor中, 因为在这个时候页面的视图还没有被渲染,放在这里是无法获取到box元素的
}
ngOnInit() {
//在初始化的时候打印box
console.log(this.box.nativeElement);
}

第二种方式---ElementRef
class="box">我是div----添加在html页面中

constructor(private el:ElementRef){
//添加在ts文件中 该方法不可放在constructor中, 因为在这个时候页面的视图还没有被渲染,放在这里是无法获取到box元素的
}
ngOnInit() {
//在初始化的时候打印box
console.log(this.el.nativeElement.querySelector('.box'));
}

  
第三种方式---ViewChildren
#divChild *ngFor="let item of list">我是div--{{item}}--添加在html页面中
constructor(){}
public
list: any[] = [1, 1, 2, 3, 4, 5, 1, 5, 2];//列表
//添加在ts文件中 该注解不可放在constructor中, 因为在这个时候页面的视图还没有被渲染,放在这里是无法获取到box元素的
@ViewChildren('divChild') divChild: QueryList<any>;

ngOnInit() { }
ngAfterViewInit() {
//在初始化试图之后打印box
console.log(this.divChild);
this.divChild.forEach((child: ElementRef) => console.log(child.nativeElement))
}




来自为知笔记(Wiz)

相关