Updating directives is required when there is a modification in the input

I created a custom directive that controls the opacity of an element based on an input value:

import { Directive, ElementRef, HostListener, Input, OnInit } from '@angular/core';
import { Observable, Subscription } from 'rxjs/Rx';

@Directive({
    selector: '[myDisabled]'
})

export class DisableDirective implements OnInit {
    private el: HTMLElement;

    @Input('myDisabled') isDisable: boolean;

    constructor(el: ElementRef) { this.el = el.nativeElement;}

    ngOnInit() {
        this.disable();
    }

    private disable() {
        this.isDisable ? this.el.style.opacity = '0.65' : this.el.style.opacity = '1';
    }
}

Although the directive works as intended, I am looking for a way to update the opacity setting when the input value changes.

To use this directive, you can add it to an element like this:

<button class="btn" [myDisabled]="!sharedDetails.isEnabled">A button !</button>

Answer №1

There are two methods to achieve this

_isDisabled: boolean;
@Input('myDisabled') 
set isDisable(value: boolean)  {
  this._isDisabled = value;
  this.disable();
}

Alternatively,

// Execute after every input update
// Review the `changes` parameter for additional information if multiple inputs are involved
ngOnChanges(changes) {
  this.disable();    
}

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

Utilizing Google's Speech-To-Text for real-time data streaming in Angular

Utilizing the Google Speech-to-Text service through @google-cloud/speech library in my node.js Firebase functions has been helpful, but I am looking to implement it for streaming data which seems impossible with Firebase functions. As a result, I plan to ...

Running the serve command necessitates being within an Angular project environment; however, despite this, Angular 4 was unable to locate a project definition

I recently cloned an old project from Github and ran into some vulnerabilities when trying to install node_module. In order to address these issues, I executed the following command: npm audit fix Despite running the above command, there were still unres ...

Divide a given number of elements within an array of arrays

Presented below is an array: [ { "id": "34285952", "labs": [ { "id": "13399-17", "location": "Gambia", "edge": ["5062-4058-8562-294 ...

Is there a way to execute Typescript tests using JasmineKarma within a TFS Build Process?

My current setup involves a web application using Angular 1.5 with bower/npm/gulp written in Typescript for our build process. The back end is a c# .net WebApi2, and both are built and deployed on TFS2015. Integrating my c# NUnit tests into the build proce ...

Differences between Angular TS Lint onInit and ngOnInit

My TS Lint issue warned me to implement the OnInit interface and included a link to this page: https://angular.io/docs/ts/latest/guide/style-guide.html#!#09-01 I'm curious, what sets apart `onInit` from `ngOnInit`? Both seem to work just fine for me. ...

Mastering regular expressions in TypeScript

My goal is to perform linting on staged files that are either .ts or .tsx and located within the src folder. I am aware that for selecting all js files one can use "*.js": [--list of commands--] inside the lint staged property. I'm curious to learn m ...

Utilizing Typescript/React to Invoke Microsoft Graph Function and Validate M365 Group Owners

As a newcomer to React and TypeScript, I am eager to utilize the Microsoft Graph API in my React/TypeScript application to verify if the logged-in user is an owner of an M365 group. This is the code snippet I currently have: import { callMsGraph } from ...

Discovering specific values for an ID using API calls in Angular (Implementing CRUD Operations in Angular with API Integration)

My current project involves CRUD operations in Angular utilizing the API created in Laravel. I have successfully added and fetched values, but encountered an issue when attempting to update values using their respective IDs. This snippet is from my app.co ...

What steps can I take to prevent receiving the error message "Certain components in XXX are not associated with the entity" in Strapi?

User I am facing an issue with my application's endpoint for adding a like to a post. The endpoint is supposed to receive the user id who liked the post and insert it, along with the number of likes (not crucial at this moment), into a database. To ac ...

I encountered an error while attempting to create an npm package from a forked repository on GitHub

Check out this GitHub repository: https://github.com/jasonhodges/ngx-gist Upon running the package command, I encounter an error: rimraf dist && tsc -p tsconfig-esm.json && rollup -c rollup.config.js dist/ngx-gist.module.js > dist/ngx- ...

Solve problems with limitations on ng2-dnd drop zones

I successfully integrated drag and drop capabilities into my Angular 4 application using the ng2-dnd library. Within my application, I have containers that can be sorted, as well as individual items within each container that can also be sorted. My goal i ...

What is the workaround for using DomSanitizer in a unit test when the component does not automatically inject it?

I have a basic component that does not utilize the DomSanitizer. Let's call it export class ExampleComponent { @Input() public safeHtml: SafeHtml | undefined; } How can I incorporate the DomSanitizer in a unit test? I have attempted to prov ...

Serialising and deserialising TypeScript types in local storage

I'm currently working on a Typescript application where I store objects using local storage for development purposes. However, I've run into some trouble with deserialization. Specifically, I have an object called meeting of type MeetingModel: ...

Maintain the specific type based on the provided data, rather than the default value, when a related generic is defined

When it comes to unit tests, I prefer a more flexible approach with dynamic generic types that eliminate the need for type casting. I want T to be open-ended, but if I specify a type, I expect to receive an exact match. For R, I need it to precisely matc ...

Accessing nested objects within an array using lodash in typescript

After analyzing the structure of my data, I found it to be in this format: {property: ["a","b"], value : "somevalue" , comparison : "somecomparison"} I am looking for a way to transform it into a nested object like so: { "properties": { "a": { ...

Could you provide insight into the reason behind debounce being used for this specific binding?

function debounce(fn, delay) { var timer return function () { var context = this var args = arguments clearTimeout(timer) timer = setTimeout(function () { fn.apply(context, args) }, delay) ...

In regards to receiving updated data with Angular 4

As a newcomer to Angular4, I have a question regarding fetching subscribed data. Within this component, there is a method called makeTableInfo(). This method is used to generate a primeng turbotable. I am trying to access column data and row data within ...

Error: JSON encountered circular structure when attempting to serialize an object of type 'ClientRequest' with a property 'socket' that references an object of type 'Socket'

Encountering an error while attempting to make a POST request to my TypeORM API using axios: TypeError: Converting circular structure to JSON --> starting at object with constructor 'ClientRequest' | property 'socket' -&g ...

Typescript custom react hook - toggling with useToggle

I developed a custom hook to toggle boolean values: import { useState } from 'react'; export function useToggle(initialValue: boolean) { const [value, setValue] = useState<boolean>(initialValue); const toggleValue = () => setValue ...

Does adding .catch resolve a promise?

Being new to typescript / javascript, I have limited knowledge about promises. My current scenario involves creating three distinct promises within a cloud-function and subsequently returning them using Promise.all([promise1, promise2, promise3]). Each of ...