如何在Angular组件中执行DOM操作? [英] How to perform DOM manipulation in Angular components?

查看:71
本文介绍了如何在Angular组件中执行DOM操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何掌握Angular(2.x版及更高版本)中的DOM元素?在打字稿中无法使用诸如addClass,removeClass等基本功能,那么我们如何在角度组件中进行这些DOM操作呢?请提出建议. TIA

How do we get hold of DOM elements in Angular (Version 2.x and above)? The basic functions like addClass, removeClass etc are not availble in typescript so how do we do these DOM manipulations in angular components? Please suggest if any. TIA

推荐答案

您可以通过以下方式使用ViewChild装饰器来访问DOM元素:

You can reach your DOM elements by using ViewChild decorator in this way:

@Component({
    ....
    templateUrl: 'mytemplate.html'
})

export class MyComponent{
  @ViewChild('selector') private someName;
  constructor() {
     //this is your dom
     //this.someName.nativeElement
  }

}

在模板类中,您必须指定谁是选择器

and in your template class you got to specify who is that selector

<div #selector> </div>

或者您可以使用ElementRef类

or you can use ElementRef class

import {Component, AfterViewInit,ElementRef} from "@angular/core";

export class MyComponent  implements  AfterViewInit {

  constructor(protected elementRef: ElementRef) {

  }

  ngAfterViewInit() {
       //you can reach your dom element by using
       //this.elementRef.nativeElement
   }
}

您可以自由使用第3方库(如Jquery)来实现typeType中的addClass,removeClass.

You are free to use 3th party libs like Jquery for addClass, removeClass within typescript.

这篇关于如何在Angular组件中执行DOM操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆