首页 > 解决方案 > 使用 typescript 访问 DOM 类或 id 的更好方法

问题描述

我正在尝试清理我的应用程序中所有与 jQuery 相关的东西。当我这样做时,我在 javascript 方法和 Angular 本机方法之间使用时感到困惑。因此,我需要对以下代码进行一些说明。

使用 jQuery 动态添加和删除类:

$('.my-class').removeClass('list-hide').addClass('list-show');

在 Javascript 中:

 var element = document.getElementByClassName('.my-class');
 element.classList.remove('list-hide');
 element.classList.add('list-show');

使用打字稿:

  const element = this.elemRef.nativeElement.querySelector('.my-class');
  element.classList.remove('list-hide');
  element.classList.add('list-show');

问题是我有很多上面的场景可以通过 DOM Id 和类名访问。如果我使用 ElementRef,我可能会写this.elementRef.nativeElement很多次。此外,在官方文档中,有人说 - '如果不支持直接访问本机元素,请使用 Render2' 并发出警告。

因此,请帮助我更好地访问 DOM 元素,而无需从我的 Angular 应用程序中进行更多重复和 jQuery。

标签: javascriptjqueryangulartypescript

解决方案


据我了解,使用 ngClass 会更容易动态添加和删除类。如果您针对特定类并希望动态执行添加或删除类,您可以执行以下操作:

在 ts 中:

filterBy:string = '';

selectedItemCode(field){
  this.filterBy = field;
}

在 html 中:

 <div (click)="selectedItemCode('random1')">Example-One</div>
 <div (click)="selectedItemCode('random2')">Example-two</div>

 <section class="my-class" [ngClass]="filterBy === 'random1'? 'list-show' : 'list-hide'">
 </section>

并回答与 elemRef.nativeElement.querySelector('my-class') 重复相关的问题:

使用 ngAfterViewInit 生命周期钩子,如下所示:

export class SomeComponent {
  public element;

  constructor(private elemRef: ElementRef){}

  ngAfterViewInit(){
    this.element = this.elemRef.nativeElement;
  }

}

在此之后,您可以直接使用 this.element.querySelector 访问 DOM 元素


推荐阅读