0

Using Angular 5.1.1, I am attempting to call a function when a checkbox changes. This method works fine for text types but for checkbox input types it always sends the value of "on" to the function even when the box is unchecked. Can anyone explain what I am doing wrong?

<input type="checkbox" name="enabled" [checked]="score?.enabled" #enabled (change)="OnFieldChanged(enabled.value)" />

Here is the component

import { Component} from '@angular/core';

@Component({
    selector: 'score',
    templateUrl: './score.component.html',
    styleUrls: ['./score.component.less']
})
export class ScoreComponent {
    public score: IScore;

    constructor() {
    }

    OnFieldChanged(value: string): void {
        var fieldValue = value;
    }
}

2 Answers 2

1

After lots of trial and error, I found the solution. You have to apply the field to [(ngModel)]. Simply passing OnFieldChanged(judge) also did not work since the boolean property was never actually updated

<input type="checkbox" name="enabled" [checked]="score?.enabled" (change)="OnFieldChanged(judge.enabled)" [(ngModel)]="score.enabled" />
Sign up to request clarification or add additional context in comments.

Comments

0

Just access score via the function as follows,

<input type="checkbox" name="enabled" [checked]="score?.enabled" #enabled (change)="OnFieldChanged(score)" />

and inside TS

OnFieldChanged(value: string): void {
        var fieldValue = value.enabled;
}

2 Comments

This is not exactly what I am looking for. I am trying to create a reusable function allowing me to capture individual input field value changes and not the whole object
i dont think you can achieve that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.