1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Validation not working in HTML file when assigned to a variable in the ts file (Angular)

Discussão em 'Angular' iniciado por mason, Julho 3, 2025.

  1. mason

    mason Guest

    I am starting with Angular basics, I have the below code to assign a class to a button based on the button name, which is received as a property like below in the button.component.ts file:

    Initial button.component.ts file:

    import { Component, Input } from '@angular/core';
    import type { ButtonProps } from './reuseable-button-types';

    @Component({
    selector: 'button',
    standalone: true,
    imports: [],
    templateUrl: './button.component.html',
    styleUrl: './button.component.css',
    })
    export class ReusableButtonComponent {
    @Input({ required: true })
    buttonProps: ButtonProps = {
    buttonName: '',
    handleClick: () => {
    //
    },
    };
    }


    Initial button.component.html file:

    <button
    (click)="buttonProps.handleClick()"
    class="reusable-button {{ buttonProps.buttonClass }}"
    type="button"
    [class.yes-button]="buttonProps.buttonName === 'Yes'"
    [class.no-button]="buttonProps.buttonName === 'No'"
    >
    {{ buttonProps.buttonName }}
    </button>


    The above code works fine with yes-button and no-button class names getting assigned to the button when the button name is 'Yes' or 'No'. But when I assign the value to a variable inside of the button.component.ts file, classes are not getting assigned as expected. See the below code:

    Modified button.component.ts file:

    import { Component, Input } from '@angular/core';
    import type { ButtonProps } from './reuseable-button-types';

    @Component({
    selector: 'button',
    standalone: true,
    imports: [],
    templateUrl: './button.component.html',
    styleUrl: './button.component.css',
    })
    export class ReusableButtonComponent {
    @Input({ required: true })
    buttonProps: ButtonProps = {
    buttonName: '',
    handleClick: () => {
    //
    },
    };

    isYesButton = this.buttonProps.buttonName === 'Yes';
    isNoButton = this.buttonProps.buttonName === 'No';
    }


    Modified button.component.html file:

    <button
    (click)="buttonProps.handleClick()"
    class="reusable-button {{ buttonProps.buttonClass }}"
    type="button"
    [class.yes-button]="isYesButton"
    [class.no-button]="isNoButton"
    >
    {{ buttonProps.buttonName }}
    </button>

    Continue reading...

Compartilhe esta Página