Angular 獲取dom方法

1.通過原生的js獲取(在ngAfterViewInit的生命週期裏面獲取,類似vue的mounted)

2.通過ViewChild裝飾器獲取

import { Component, OnInit, AfterViewInit, ViewChild, ElementRef } from '@angular/core';

//引入 ViewChild, ElementRef (表示dom的ref的類型)

@ViewChild('dom') myDom: ElementRef; //定義此dom變量

<p #dom>111111</p>  // html中命名的方式

ngAfterViewInit(): void {

   this.myDom.nativeElement.style.color = '#ffae00';
   console.log(this.myDom.nativeElement.innerHTML);

}

//在ngAfterViewInit的生命週期裏面應用,有個nativeElement對象

3.ViewChild裝飾器也能獲取組件的dom實例

import { Component, OnInit, AfterViewInit, ViewChild } from '@angular/core';

//不需要ElementRef

@ViewChild('detail') myDom: any;  //定義組件實例

ngAfterViewInit(): void {

  this.myDom.run();

}

//子組件的方法可以直接使用

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章