angular 獲取DOM元素 多種方式


第一種方式 --- ViewChild

<div #box>我是div----添加在html頁面中</div>

@ViewChild('box') box: ElementRef;
constructor(){
//添加在ts文件中 該方法不可放在constructor中, 因為在這個時候頁面的視圖還沒有被渲染,放在這里是無法獲取到box元素的
}
ngOnInit() {
//在初始化的時候打印box
console.log(this.box.nativeElement);
}

第二種方式--- ElementRef

<div class="box">我是div----添加在html頁面中</div>

constructor(private el:ElementRef){
//添加在ts文件中 該方法不可放在constructor中, 因為在這個時候頁面的視圖還沒有被渲染,放在這里是無法獲取到box元素的
}
ngOnInit() {
//在初始化的時候打印box
console.log(this.el.nativeElement.querySelector('.box'));
}

  
第三種方式---ViewChildren

<div #divChild *ngFor="let item of list">我是div--{{item}}--添加在html頁面中</div>
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))
}







免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM