angulartypescriptdirectiveangular12angular-ngselect

NG-SELECT disabled not working with directive using angular 12


I am trying to disable ng-select through directive. Can anyone suggest How can I do this?

This is my code and here is the example. which was I trying.

setTimeout(() => {
  const selectElement = this.elementRef.nativeElement;
  if (this.elementRef.nativeElement.tagName === 'NG-SELECT') {
    console.log('selectElement :', this.elementRef.nativeElement);
    this.renderer.setProperty(selectElement, 'disabled', true);
    this.renderer.setProperty(selectElement, ' ng-select-disabled', '');
    this.renderer.addClass(selectElement, 'disabled');
    const inputEle = this.elementRef.nativeElement.querySelector('input');
    this.renderer.setProperty(inputEle, 'disabled', true);
  }
}, 1000); 

I tried many ways But I need to do this with directives Can anyone know how can i do this with directive?

Can anyone suggest how can I do this?


Solution

  • Working StackBlitz

    just retrieve the host component from the constructor, so here NgSelectComponent and use the method setDisabledState

    import { Directive, ElementRef, Renderer2 } from '@angular/core';
    import { NgSelectComponent } from '@ng-select/ng-select';
    
    @Directive({
      selector: '[appCurrencySelect]',
    })
    export class CurrencySelectDirective {
      constructor(private elementRef: ElementRef, private el: NgSelectComponent) {
        setTimeout(() => {
          const selectElement = this.elementRef.nativeElement;
          if (selectElement.nativeElement.tagName === 'NG-SELECT') {
            this.el.setDisabledState(true);
          }
        }, 1000);
      }
    
      ngAfterViewInit() {}
    }