在上面的代码中,我想显示UI中initialstatus
数组中提到的复选框的初始状态,然后我可以随机更改initialStatus
中的任何复选框..这应该反映在{{1数组。
initialstatus
组件:
<div class="container" [hidden]="submitted">
<form ng-app="app" (submit)="onSubmit()">
<div *ngFor="let initial of initialState,let j = index" >
<div *ngIf="initial.checked==true">
<button class="button" type="button">Device{{j}} </button>
<label class="switch">
<input type="checkbox" name= "checked" id="checkbox_category" checked />
<div class="slider round"></div>
</label>
<br/>
</div>
<div *ngIf="initial.checked==false">
<button class="button" type="button">Device{{j}}</button>
<label class="switch">
<input type="checkbox" id="checkbox_category" name= "checked" />
<div class="slider round"></div>
</label>
<br/>
</div>
</div>
<button class="buttons" type="submit">Submit</button>
<button (click)="resetAll()">Reset</button>
<button (click)="selectAll()">selectALL</button>
</form>
</div>
但它没有发生......我能够单独显示初始状态,并且在UI中进行的任何更改都会反映在Array中。
要实现export class DashboardComponent{
submitted:boolean;
model= new SendDetails();
initialState:any = [{checked:true},{checked:false},{checked:true},{checked:false},{checked:true},{checked:false}];
intendedDeviceStatus: any = this.initialState;
constructor(
) {
this.submitted=false;
}
onSubmit(){
this.submitted=true;
this.model.initSession();
}
resetAll() {
this.initialState.forEach((initial:any) => {
initial.checked = false;
}
)}
selectAll() {
this.initialState.forEach((initial:any) => {
initial.checked = true;
}
)}
}
}
显示,我的输入标签如上所述,要实现双向绑定,我需要将InitialStatus
添加到输入标签中
在我的输入标签中。但我无法同时实现这两个目标。如何实现双向绑定并将一些复选框显示为已选中,而将少数复选框显示为未选中。
答案 0 :(得分:1)
input type =“checkbox”checked = {{initial.checked}}。这会将初始检查状态设置为true或false,具体取决于数组中的内容。当用户更改时,也会反映在您重复的数组中。
答案 1 :(得分:0)
你可以通过一个循环来完成这一切
模板:
<form (submit)="register()">
<div *ngFor="let initial of initialState,let j = index" >
<button class="button" type="button">Device{{j}} </button>
<label class="switch">
<input type="checkbox" name= "checked[{{j}}]" [(ngModel)]='initialState[j].checked'/>
<div class="slider round"></div>
</label>
<br/>
</div>
<button class="buttons" type="submit">Submit</button>
</form>
组件:
initialState:any = [{'checked':true},{'checked':false},{'checked':true},{'checked':false},{'checked':true},{'checked':false}];
register()
{
console.log(this.initialState);
}
稍微更改了initialState:any
。
对于plunker,只需更改此行:
<input type="checkbox" name="checked" [checked]='initialState[j].checked' (change)='initialState[j].checked = $event.target.checked' />
您也可以在此处查看:Plunker