我正在尝试清理应用程序中所有与jQuery相关的内容。当我这样做的时候,我很困惑在javascript方法和有角度的本机方法之间使用。因此,我需要对以下代码进行一些说明。
使用jQuery动态添加和删除类:
$('.my-class').removeClass('list-hide').addClass('list-show');
在Java语言中:
var element = document.getElementByClassName('.my-class');
element.classList.remove('list-hide');
element.classList.add('list-show');
使用TypeScript:
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。
答案 0 :(得分:2)
As far I understand going with ngClass would be easier for dynamically adding and removing class. If you are targeting to a particular class and want to perform add or remove class dynamically, you could do something like below:
In ts:
filterBy:string = '';
selectedItemCode(field){
this.filterBy = field;
}
In 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>
And to answer the question related to repetition of elemRef.nativeElement.querySelector('my-class'):
use a ngAfterViewInit life cycle hook like below:
export class SomeComponent {
public element;
constructor(private elemRef: ElementRef){}
ngAfterViewInit(){
this.element = this.elemRef.nativeElement;
}
}
After this you can use this.element.querySelector directly to access DOM elements