我是新手,所以如果我要说/问一些非常愚蠢的事情,请原谅。 我按照以下示例在复选框中添加了复选框: enter link description here
一切正常,我可以将复选框的ID保存到数据库中。 问题是,当我尝试修改表单时,无法检查之前已检查并保存到数据库中的复选框(字符串列表,我知道这不行,但现在我将其保留为这样)。 我收到列表,将其转换为数组以进行迭代,然后尝试将控件的value设置为true,但没有任何效果。 有人能帮我吗? 这些是我的文件: addmodify.component.ts:`
public natura = [
{ id: 1, name: 'si'},
{ id: 2, name: 'af'},
{ id: 3, name: 'erg'},
{ id: 4, name: 'rid'},
{ id: 5, name: 'ridc'},
{ id: 6, name: 'qual'},
{ id: 7, name: 'Ridte'},
{ id: 8, name: 'Alt'}
];
constructor(
private _fb: FormBuilder,
private _avRoute: ActivatedRoute,
private _suggerimentoService: SuggerimentoService,
private _nuovoPartecipanteService: NuovoPartecipanteService,
private toasterService: ToasterService,
private translate: TranslateService,
private _router: Router) {
const controls = this.natura.map(c => new FormControl(false));
this.suggerimentoForm = this._fb.group({
natura: new FormArray(controls, minSelectedCheckboxes(1))
});
controls[0].setValue(true); // this works, on init it checks the first checkbox.
}
ngOnInit() {
if (this.id > 0) {
this._suggerimentoService.getSuggerimentoById(this.id)
.subscribe(resp => {
const controls = this.natura.map(c => new FormControl(false));
const listNatura = resp.natura.split(','); // here resp.natura is ="4,5" and then listNatura will be an array with those 2 values
// this is how I tried to set the checkboxes checked but it's wrong
listNatura.forEach(function (value) {
console.log('valore=',value);
controls[0].setValue(true);
});
resp.natura = this.natura; // I have to do this because if not (if I leave resp.natura a string) I'm getting an error.
this.suggerimentoForm.setValue(resp);
}, error => this.errorMessage = error);
}
}
这是我的html文件:
<form class="k-form" [formGroup]="suggerimentoForm" (ngSubmit)="save()" #formDir="ngForm" novalidate>
<div formArrayName="natura" *ngFor="let nat of suggerimentoForm.controls.natura.controls; let i = index">
<input type="checkbox" [formControlName]="i" class="k-checkbox " value="{{natura[i].id}}" id="{{natura[i].id}}">
<label class="k-checkbox-label" for="{{natura[i].id}}">{{natura[i].name}}</label>
</div>
</form>