问题描述:

I have the following directive which after the view is checked it adds a class to the element checkbox-unselected. Then when the element is clicked it calls a method which should remove the class checkbox-unselected and replace it with another class checkbox-selected. While the new class is added as expected the old class isn't removed. I can't find any documentation on this method but from what I have been able to assertion setting the value of the third parameter isAdd to false should tell the method to remove the provided class, but that doesn't happen.

export class SharedCustomCheckboxDirective implements AfterViewChecked {

@Input('cmgSharedCustomCheckbox') isChecked: string;

constructor( private element: ElementRef,

private renderer: Renderer ) { }

public ngAfterViewChecked(): void {

this.renderer.setElementClass(this.element.nativeElement.children[0], 'checkbox-unselected', true);

}

@HostListener('click') click(): void {

if (this.isChecked !== 'true') {

this.renderer.setElementClass(this.element.nativeElement.children[0], 'checkbox-unselected', false);

this.renderer.setElementClass(this.element.nativeElement.children[0], 'checkbox-selected', true);

}

}

}

网友答案:

The issue was caused by me using AfterViewChecked, which is called repeatedly, adding that class back on the element after it was removed. Changing out to AfterViewInit resolved the issue.

相关阅读:
Top