码迷,mamicode.com
首页 > 其他好文 > 详细

angular操作Dom

时间:2019-11-29 15:58:36      阅读:93      评论:0      收藏:0      [点我收藏+]

标签:const   view   element   void   方法   引入   xxx   struct   ini   

1.通过原生JS操作

在ts文件中,在ngAfterViewInit()生命周期函数中(此时已经生成了DOM节点),通过原生js的方式可以获取该节点

const div1: any = document.getElementById(‘box‘); // any必须。否则报错

 

2、通过viewChild来获取节点

html:定义一个#xxxx

<div #getChild>
  我是viewChild的数据
</div>

ts:引入viewChild,通过viewChild定义设置的#xxxx。此时对应的节点可以通过this.getChild.naticeElement来获取

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

@Component({
  selector: ‘app-dom‘,
  templateUrl: ‘./dom.component.html‘,
  styleUrls: [‘./dom.component.less‘]
})
export class DomComponent implements OnInit {
  @ViewChild(‘getChild‘) getChild: any;
  constructor() { }
  public debug: any = true;
  ngOnInit(): void {
  }
   ngAfterViewInit(): void { // 视图加载完成后触发的方法 dom加载完成
 
     console.log(this.getChild.nativeElement.innerHTML);
   }

}

 

angular操作Dom

标签:const   view   element   void   方法   引入   xxx   struct   ini   

原文地址:https://www.cnblogs.com/cazj/p/11958023.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!