Angular 获取dom方法

1.通过原生的js获取(在ngAfterViewInit的生命周期里面获取,类似vue的mounted)

Angular 获取dom方法_第1张图片

Angular 获取dom方法_第2张图片

2.通过ViewChild装饰器获取

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

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

@ViewChild('dom') myDom: ElementRef; //定义此dom变量

111111

// 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();

}

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

 

你可能感兴趣的:(angular,dom,ng)