javascript - 使用 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。
解决方案
据我了解,使用 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 元素
推荐阅读
- c# - 如何从 wsdl 创建代码并分离 Xsd
- c# - UWP 文本框中的光标行为异常
- apache-nifi - selecehiveql 处理器 nifi 中的默认线程数
- c++ - 循环内控制台中的输入和输出
- saml-2.0 - Aws Cognito 的 SAML 属性映射 - 注册或登录有效,但不能同时使用
- ios - 添加对象后如何更新tableview
- excel - VBA R1C1公式计算与另一个工作表中的单元格
- asp.net-web-api - 枚举值不解析时如何将枚举作为字符串绑定失败处理
- c# - 运行时激活的类中的 MEF 导入属性 null
- laravel - Laravel mix 为 css 和 js 文件启用哈希