Search code examples
htmlcheckboxdata-bindingtypescriptangular

Launch an event when checking a checkbox in Angular2


I'm newbie in Angular2 and in web globally , I want to launch an action that changes an oject paramater value in the Database when checking a checkbox and or unchecking it using Material-Design, I tried with [(ngModel)] but nothing happened. the idea is that i have to add some propositions with checked | unchecked status to tell if it is a true or false proposition. Here is the proposition model

export class PropositionModel {
    id:string;
    wordingP:string; // the proposition
    propStatus:Boolean; // the proposition status
}

here is the Html code for a proposition :

<div class="uk-width-xlarge-1-1 uk-width-medium-1-2">
                <div (submit)="addProp1()" class="uk-input-group">
                    <span class="uk-input-group-addon"><input type="checkbox"  data-md-icheck/></span>
                    <label>Proposition 1</label>
                    <input [(ngModel)]="proposition1.wordingP" type="text" class="md-input" required class="md-input"/>
                </div>
            </div>

here is the TypeScript code for adding the proposition:

addProp1() {
        this.proposition1 = new PropositionModel();
        this.proposition1.propStatus = false;
        this.propositionService.addProposition(this.proposition1)
            .subscribe(response=> {
                console.log(response);
                console.log(this.proposition1);
                this.proposition1 = new PropositionModel();})
    }

And as you can see i made it a false by default for the proposition status and I want to change it once i checked the proposition. Here is an image how it looks for a better issue understanding. enter image description here

Any help Please ?


Solution

  • StackBlitz

    Template: You can either use the native change event or NgModel directive's ngModelChange.

    <input type="checkbox" (change)="onNativeChange($event)"/>
    

    or

    <input type="checkbox" ngModel (ngModelChange)="onNgModelChange($event)"/>
    

    TS:

    onNativeChange(e) { // here e is a native event
      if(e.target.checked){
        // do something here
      }
    }
    
    onNgModelChange(e) { // here e is a boolean, true if checked, otherwise false
      if(e){
        // do something here
      }
    }