【发布时间】:2017-12-22 09:35:54
【问题描述】:
我有一个由复选框动态生成的表单,以及一个从服务器获取表单数据的初始 get 请求(哪些复选框被选中和未选中,由值 0 或 1 定义为真或假) 当我单击一个复选框时,它应该切换(选中/未选中)以及发送正确的 put 请求(与当前值相反(0 到 1、1 到 0)。 现在,所有未选中的复选框都按预期运行。但是从初始获取选中的框,单击一次,然后取消选中并在应该发送 0 时发送 1,如果再次单击,则保持未选中状态但发送正确的输出 0,然后该复选框从那时起正确运行.发生了什么导致第一次点击只有选中的框?
比较
places;
ready = false;
countriesForm: FormGroup;
constructor(private whiteListService: WhiteListService) {}
ngOnInit() {
// get places list with status'
this.whiteListService.getList()
.subscribe(
(response: Response) => {
console.log(response.statusText);
this.places = response.json();
this.createList(this.places.countries);
},
(error) => console.log(error)
);
}
createList(places) {
// assign this.places for dom binding access
this.places = places;
console.log(places)
this.countriesForm = new FormGroup({});
for (let i = 0; i < this.places.length; i++) {
this.countriesForm.addControl(
this.places[i].name, new FormControl()
);
}
this.ready = true;
}
toggleAllowed(place, event) {
// send authorization of country to server
console.log('allow before switch', place.allow);
place.allow === 1 ? place.allow = 0 : place.allow = 1;
console.log('allow after switch', place.allow);
console.log(this.places);
this.whiteListService.sendAllow(place.code, place.allow)
.subscribe(
(response) => console.log(response),
(error) => {
console.log(error);
place.allow = !place.allow;
}
);
}
}
html
<div class="geo-list">
<div class="content-box container">
<form *ngIf="ready" [formGroup]="countriesForm">
<div class="place" *ngFor="let place of places">
<input
type="checkbox"
formControlName="{{place.name}}"
value="{{place.allow}}"
(change)="toggleAllowed(place, $event)"
[checked]="place.allow == 1"
>
{{ place.name }} | {{ place.code }} | {{ place.continent }} | {{ place.allow }}
</div>
</form>
</div>
</div>
【问题讨论】:
标签: angular checkbox angular-reactive-forms