Angular 12 Directive causing NG-SELECT disabled feature to malfunction

Looking for a way to disable ng-select using a directive. Does anyone have any suggestions on how to accomplish this?

Here is the code I have been working with, along with an example that I was trying to implement.

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 have tried various methods without success. Ideally, I would like to achieve this using directives. Any insights on how this can be achieved through directives?

  • [disabled]="true" => works with ngModel
  • [readonly]="true" => works with formControlName
  • However, not working with directive.

If anyone has any tips or solutions, please share them!

Answer №1

Check out the StackBlitz demo

To make this work, simply access the host component in the constructor using NgSelectComponent and utilize the setDisabledState method.

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() {}
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dynamically passing output placeholders through ng-content in an Angular component template

Can a component handle dynamic projection in this way? <my-component [date]="2022-03-22"> <p>This particular date falls on a <strong #dayName></strong>! It is in week number <span #weekNum></span> of year &l ...

Testing the throwing of errors when running Karma by utilizing sinon.spy on global functions like parseInt

I'm currently facing an issue with monitoring the usage of parseInt within my function. This is a Proof of Concept for integrating TypeScript into our company's workflow. I've tried following two different tutorials on testing Sinon, but no ...

When utilizing Typescript to develop a form, it is essential to ensure that the operand of a 'delete' operator is optional, as indicated by error code ts(279

Can someone help me understand why I am encountering this error? I am currently working on a form for users to submit their email address. export const register = createAsyncThunk< User, RegisterProps, { rejectValue: ValidationErrors; } > ...

ERROR: PipeError - Conversion of "Invalid Date" to a date is not possible for the DatePipe

While attempting to format a date with time, I ran into an error. The way I am sending the request is as follows: created = this.datePipe.transform(dateCreated, 'yyyy-MM-ddTHH:mm'); I require the time in order to consume a service that necessi ...

Using TypeScript, define a React function component by specifying its name as a type

While working in React.js, I encountered an issue with my Function Component. When I attempted to use the function name as the type, it resulted in an error. Here is a snippet of the code: import * as React from "react"; import { render } from "react-dom ...

Troubleshooting Angular Build Errors: Integrating Three.js

Upon setting up a new Angular application and integrating three along with @types/three, I proceeded to create a basic component. However, upon executing ng build --prod, the following errors are displayed: ERROR in node_modules/three/src/core/BufferAttri ...

Leveraging Angular and HTML to efficiently transfer the selected dropdown value to a TypeScript method upon the user's button click

I am experiencing difficulty accessing the .value and .id properties in {{selectItem}} in order to send them back to the typescript for an HTTP post at a later time. Although there are no specific errors, I have encountered exceptions and have tried search ...

How can we leverage RxJS combineLatest for observable filtering?

I'm exploring the possibility of utilizing combineLatest in an Angular service to eliminate the need for the activeFiler$ switch block (The service should achieve the same functionality). Currently, this is the structure of the component design (stack ...

Angular and RxJS: Ensuring continuous interval execution in the event of an error

Every 10 seconds, I make a call to a RESTful service through an Angular service called "myservice" and a function called "foo." ngOnInit () { interval (10000).pipe (startWith (0), mergeMap (obs => this.myservice.foo ())).subscribe (resp = ...

Unlocking NgControl in an Angular Material custom form field control with Angular 10

I am attempting to utilize NgControl within a custom Angular Material Form Field Control: constructor( @Self() @Optional() public ngControl: NgControl, private fb: FormBuilder, private fm: FocusMonitor, private elRef: ElementRef<HTMLElem ...

Setting text in a datetime picker with ngx-mat-datetime-picker in an Angular application is a straightforward process

I've been utilizing the ngx-mat-datetime-picker library from angular-material-components to enable datetime selection. It's functioning effectively, but I'm searching for a way to insert text preceding the hour and minute inputs, such as &ap ...

Leverage the source code of Angular 2 in your project for seamless integration

Currently in the process of setting up Angular with npm: npm install @angular... Encountering an issue where the TypeScript source files are not included. I would like to have access to debug the code using the TypeScript source files (with source maps). ...

Guide to setting up a trigger/alert to activate every 5 minutes using Angular

limitExceed(params: any) { params.forEach((data: any) => { if (data.humidity === 100) { this.createNotification('warning', data.sensor, false); } else if (data.humidity >= 67 && data.humidity <= 99.99) { ...

Modify/remove table using a popup window

My goal was to include edit and delete buttons within a table. When these buttons are clicked, a popup window opens allowing us to modify the values and then update them in the table using Angular. ...

Attempting to utilize the subscribe function in the parent component proves to be unsuccessful, yet it successfully functions in the child component within the realm of rx

I have a main chat-component that displays two chat modules, and I am monitoring changes in a service from the main component using the subscribe method. I'm not sure why, but when I subscribe in the child component, it works and I can see the consol ...

Utilizing the combineReducers() function yields disparate runtime outcomes compared to using a single reducer

Trying to set up a basic store using a root reducer and initial state. The root reducer is as follows: import Entity from "../api/Entity"; import { UPDATE_GROUPING } from "../constants/action-types"; import IAction from "../interfaces/IAction"; import IS ...

Is there a way to incorporate several select choices using specific HTML?

I am currently trying to dynamically populate a select tag with multiple option tags based on custom HTML content. While I understand how to insert dynamic content with ng-content, my challenge lies in separating the dynamic content and wrapping it in mat ...

Resolving undefined in Ionic 4: Returning Data from Modal

I'm attempting to create a modal window that utilizes a radio group. When a user selects a value from the radio group, I want the modal to return the selected object. Here is the code for the radio group page and HTML: export class PopoverstationsPa ...

Restricting number input value in Vue using TypeScript

I have a component that looks like this: <input class="number-input py-1 primary--text font-weight-regular" :ref="'number-input-' + title" @keypress="onKeyPressed" :disabled="disabled& ...

Steps to remove the Angular workspace created in the directory C:Usersusername are as follows:

By mistake, I executed the angular command "ng new client" in the c:\users<username> directory. How can I remove it from there? I actually intended to create it in my project folder instead. ...