Checked and unchecked checkbox in Angular 2 by boolean value

Viewed 28525

I would like to make checkbox in Angular 2 automatically checked or unchecked. When the value is 1 the checkbox will check and this one is 0 the checkbox will automatically uncheck.

public LightControl() {
    this.dataLight = this._LightService.AutoLightController(this._ConnectService.SocketInstanse())
        .subscribe(data => {
            this.temp = JSON.stringify(data['status']);
        })
}

HTML:

 <div class="togglebutton">
    <label> <input type="checkbox" [checked]="temp(change)="temp">Light</label>
 </div>
  • When temp value is true it checked, but when temp is false, it didn't uncheck automatically.
4 Answers

Use checked property of input field. Bind a boolean variable to checked property of input checkbox. Use observable concept, and subscribe the data variable which will trigger the check box visibility of input field. [checked]=‘yourModel.isChecked’ In subscribe method assign the current status to this isChecked property of yourModel. And based on the current value of this property the check box will be checked or unchecked.

observableVariable.subscribe( data => { process data or according to processed data, assign the status to

yourModel.isChecked = status

});

Try this:

<input type="checkbox" [checked]="temp == 1 ? '' : null">

This will show the checked attribute only when temp is 1.

Related