Reputation: 53
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>
Upvotes: 4
Views: 31337
Reputation: 101
Try this:
<input type="checkbox" [checked]="temp == 1 ? '' : null">
This will show the checked attribute only when temp is 1.
Upvotes: 1
Reputation: 2539
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
});
Upvotes: 2
Reputation: 23
angular 2 the checkbox value is true, the checkbox is selected:
<div class="togglebutton">
<label> <input type="checkbox" [value]="true" [(ngModel)]="temp">Light</label>
</div>
if temp is boolean, you must use [value]="true"
, when the temp is true, the checkbox is selected, if the temp is false, the checkbox is not selected, if you use value="true"
, the temp is string.
Upvotes: 0
Reputation: 28338
EDIT:
First create a SharedModule
:
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {RouterModule} from '@angular/router';
@NgModule({
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule,
RouterModule
],
exports: [
CommonModule,
FormsModule,
ReactiveFormsModule,
RouterModule
],
declarations: []
})
export class SharedModule {}
Then import this SharedModule
into the module of the route that needs to use the checkbox.
Now you will be able to use angular specific directives such as ngModel
.
<input type="checkbox" [(ngModel)]="isChecked">
In component:
this.isChecked = Number(data['status']) === 0 ? false : true;
Upvotes: 1