angulartypescriptangular-renderer2

Cannot read properties of undefined (reading 'add') while adding a class through angular's renderer2


Here's my code:

@Directive({
  selector: '[appDropdown]',
})

export class DropdownDirective {
  isClassApplied: boolean;
  @Input('appDropdown') className: string;

  constructor(private renderer: Renderer2, private elRef: ElementRef) {
    this.isClassApplied = false;
  }

    @HostListener('click') onClickAddClass() {
        if (!this.isClassApplied) {
            this.isClassApplied = true;
            this.renderer.addClass(this.elRef, this.className);
        } else {
            this.isClassApplied = false;
            this.renderer.removeClass(this.elRef, this.className);
        }
    }
}

Here's the html: CodePen Link

It is giving me an error when trying to add a class on the elRef. Can anyone please tell me what's wrong in this.


Solution

  • What happens here is i haven't given the correct argument to addClass function. I must have to pass the element on which the directive sits on. And that should be found under the nativeElement of the ElementRef.

    So the code look like this:

    @Directive({
      selector: '[appDropdown]',
    })
    
    export class DropdownDirective {
      isClassApplied: boolean;
      @Input('appDropdown') className: string;
    
      constructor(private renderer: Renderer2, private elRef: ElementRef) {
        this.isClassApplied = false;
      }
    
        @HostListener('click') onClickAddClass() {
            if (!this.isClassApplied) {
                this.isClassApplied = true;
                this.renderer.addClass(this.elRef.nativeElement, this.className);
            } else {
                this.isClassApplied = false;
                this.renderer.removeClass(this.elRef.nativeElement, this.className);
            }
        }
    }
    

    Now, it should work as expected.