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

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

问题描述

我们如何在 Angular(2.x 及更高版本)中获取 DOM 元素?addClass、removeClass 等基本函数在 typescript 中不可用,那么我们如何在 angular 组件中进行这些 DOM 操作?如果有请建议.TIA

解决方案

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

@Component({....templateUrl: 'mytemplate.html'})导出类 MyComponent{@ViewChild('selector') private someName;构造函数(){//这是你的dom//this.someName.nativeElement}}

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

或者你可以使用 ElementRef 类

import {Component, AfterViewInit,ElementRef} from "@angular/core";导出类 MyComponent 实现 AfterViewInit {构造函数(受保护的元素引用:元素引用){}ngAfterViewInit() {//你可以通过使用到达你的dom元素//this.elementRef.nativeElement}}

您可以在打字稿中自由使用第 3 方库,如 Jquery 的 addClass、removeClass.

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

解决方案

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>

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
   }
}

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

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

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