Using @HostBinding based on the @Input() condition

I'm attempting to link the CSS class foo to my parent component by utilizing @HostBinding based on a condition I evaluate against a dynamic variable. However, I am struggling to get it to function as expected.
Here are the different approaches I have already tested:

export class MyComponent {
    @Input()
    public input: string;

    @HostBinding('class.foo')
    public isFoo: Boolean = this.checkIfCorrectInput();

    constructor() {
    }

    private checkIfCorrectInput(){
        return (this.input != 'not correct');
    }
}

Is there a method I could use to make this work? Perhaps listening for changes in the input value?

Answer №1

One possible solution is to create a getter and setter for the @Input property and use the setter to set the isFoo variable accordingly.

export class MyComponent {   
     @Input()
        public get input (): string {
          return this._input;
        }
        public set input (val: string) {
          this._input = val;
          // check the input value and set isFoo accordingly
          this.isFoo = (val !== 'not correct');
        }

        @HostBinding('class.foo')
        public isFoo: Boolean = false; // initialize as false

        constructor() {
        }
    }

Answer №2

You're on the right track with your approach:

export class MyComponent {
    @Input()
    public input: string;

    @HostBinding('class.foo')
    public get isFoo(): Boolean {
        return this.input !== 'not completely accurate';
    }

}

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

The build script does not execute during the creation of a Node.js and React application in Visual Studio

I am currently following a detailed guide on setting up Visual Studio 2019 to develop a Node.js-React application. The link to the guide can be found here: https://learn.microsoft.com/en-us/visualstudio/javascript/tutorial-nodejs-with-react-and-jsx?view=vs ...

Managing errors in ErrorHandler and addressing them in HttpInterceptor

Can you explain the difference between error handling methods in Angular 7? Is it necessary to handle global errors in HttpInterceptor and also in Angular's built-in ErrorHandler? In the HttpInterceptor, what types of errors can be handled, and in the ...

Verify if an object property is called with the toHaveBeenCalledWith() function in Jasmine

Recently started incorporating Jasmine into my workflow and I am trying to verify if my method was called with an object that includes a MyProperty property. Currently, my setup looks like this: expect(service['method']).toHaveBeenCalledWith(jasm ...

Tips for emptying the search field in primeng multiselect widget

Is it possible to reset the search input field in primeng multiselect? I've been referring to the tutorial on primeng multiselect provided in the following article. https://www.primefaces.org/primeng/showcase/#/multiselect https://i.stack.imgur.com ...

What steps can be taken to resolve the error message "Using 'null' as an index type is not allowed."?

In my TypeScript code, I have a variable called lang declared as a string type value, and a variable called direction declared as an object with two elements. I also have a function that is supposed to return the value of the direction object based on th ...

The conflict arises when importing between baseUrl and node_modules

I am currently working on a TypeScript project with a specific configuration setup. The partial contents of my tsconfig.json file are as follows: { "compilerOptions": { "module": "commonjs", "baseUrl": &quo ...

Angular: Observing DOM changes through observables

I have been exploring ways to track changes in the DOM of my angular component. Utilizing observables to capture those changes into a typescript variable, although uncertain if that's the right approach. Here is how I've set it up: app.componen ...

Customize the text for the material icon

Can I customize an icon by using the following code: import FiberNewIcon from "@mui/icons-material/FiberNew"; Is there a way to add custom text to the icon? ...

Ensuring Commitments in the ForEach Cycle (Typescript 2)

Having trouble with promise chains after uploading images to the server in Angular 2 and Typescript. Let's come up with some pseudo-code: uploadImages(images):Promise<any> { return new Promise((resolve, reject) => { for (let imag ...

Linking Angular 2 Production Mode to the vendor directory

I am currently working on an Angular2 project using the angular-cli npm package. To upload the app to the server, I used the following commands: ng build --prod and ng serve --prod. However, after uploading the dist folder to the server and trying to acc ...

``Is it possible to iterate through a collection of objects using a loop?

I am facing an issue with updating a global array that contains objects, where each object includes another array. My goal is to update the main array with values from the arrays within the objects following a specific logic! generalArray = [{name:String, ...

Angular's mechanism for detecting changes in a callback function for updates

I have come across a puzzling scenario regarding a basic issue. The situation involves a simple component with a boolean property that is displayed in the template of the component. When I update this property within a callback function, the property is up ...

Creating a JSON structure using an array in Typescript

Here is an example of my array structure: [ { "detail": "item1", "status": "active", "data": "item1_data" }, { "detail": "item2", "status": ...

What steps can be taken to ensure that the requestAnimationFrame function does not redraw the canvas multiple times after a button click?

I am currently working on a project where I am drawing a sin wave on a canvas and adding movement to it. export class CanvasComponent implements OnInit { @ViewChild('canvas', { static: true }) canvas: ElementRef<HTMLCanvasElement>; ...

The process of automatically formatting Typescript has transformed into an unfortunate auto-discarding action

Typescript autoformatting has become a concerning issue. Whenever I input quoted strings (" or `), the code surrounding it seems to temporarily glitch, with other strings appearing as code. This problem has recently escalated, particularly with strings li ...

Express.js Router does not recognize the term 'this'

Greetings and thank you for taking the time to peruse through this. I am venturing into the realm of express.js and typescript and have stumbled upon an intriguing issue. I am currently trying to unravel the mystery behind why 'this' is undefined ...

To set up Ionic on your project, run the command `npm install

After setting up a new Ionic project, I included the Android platform using the command ionic cordova platform add android. This action added the following entry in the config.xml file: <engine name="android" spec="~6.1.2" /> Prior to this, I came ...

Issue with Material UI v5: "spacing" property not found on custom theme object

My current setup involves using version 5 of material ui, where I have customized a theme and applied it to all my components. However, when trying to add padding to a paper element in one of my components based on the theme, I encountered the following e ...

The type 'TaskListProps[]' cannot be assigned to type 'TaskListProps'

I'm struggling with handling types in my TypeScript application, especially with the TaskListProps interface. export default interface TaskListProps { tasks: [ { list_id: string; title: string; description: string; status ...

What is the reasoning behind ngOnInit not being the initial lifecycle hook in Angular?

As a beginner in Angular 2, I'm curious about why ngOnInit is not the initial hook called after a component or directive's constructor? Reference: https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html ...