我正在尝试清理我的应用程序中所有与 jQuery 相关的东西。当我这样做时,我对在 javascript 方法和 Angular native 方法之间使用感到困惑。因此,我需要对以下代码进行一些说明。
使用 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');
使用 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
。
此外,在官方文档中说 - “如果不支持直接访问 native 元素,请使用 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 生命周期钩子(Hook):
export class SomeComponent {
public element;
constructor(private elemRef: ElementRef){}
ngAfterViewInit(){
this.element = this.elemRef.nativeElement;
}
}
之后你可以直接使用 this.element.querySelector 来访问 DOM 元素
关于javascript - 使用 typescript 访问 DOM 类或 id 的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55537194/