提问者:小点点

Angular:向跨度选择器添加类


我有下面的代码,我想添加一个类到一个跨度选择器,但我有这个错误

无法读取null的属性“class list”

<th *ngFor="let column of columns;"
    <ng-container *ngIf="column?.sortable">
        <span [id]="'sort-'+column?.field" (click)="sortArray(column?.field)"></span>
    </ng-container>
</th>
if (this.columns) {
   this.columns.forEach(column => {
       if (column.sortable) {
           const parent: HTMLElement = document.getElementById("sort-" + column.field);

           this.renderer.setElementClass(parent, "sorting_asc", true);
       }
   })
}

共1个答案

匿名用户

我认为您的代码过于复杂了,您正在使用angular,我认为使用document.getElementById()访问DOM元素不是一个好的实践。

为了使代码正常工作,您需要确保在访问DOM元素之前已经加载了视图。您需要将代码移动到AfterViewInit生命周期钩子。

下面是我如何重构代码

<th *ngFor="let column of columns;"
    <ng-container *ngIf="column?.sortable">
        <span [class.sorting_asc]="column?.sortable" (click)="sortArray(column?.field)"></span>
     </ng-container>
</th>

我们只需绑定到[class.sorting_asc]=“column?。sortable”,并让angular为我们应用类