I have multiple checkboxes on edit form whose selected values I am sending to backend and retrieving database values on page load and showing checkbox checked for retrieved values.
template code
<div class="col-lg-12">
<div class="form-group">
<label class="w-100">Type of events <b style="color: red">*</b></label>
<div class="pretty_wrapper">
<div class="pretty p-default" *ngFor="let event of EventTypes index as i">
<input type="checkbox"
[name] = "'EventType_'+event.id"
[value]="event.id"
(change)="onCheckboxChange($event)"
[attr.checked]="isChecked(event.id)"
/>
<div class="state d-flex" >
<label> </label>
</div>
</div>
</div>
<div class="text-danger" *ngIf="submitted && eventArray.length === 0" >
Event type is required, select atleast one value.
</div>
</div>
</div>
component code
...
selectedEventIds:any = [];
public eventArray:any = [];
...
ngOnInit() {
...
if (results['status'] === true) {
for (let event_type of results.data.event_type) {
this.selectedEventIds.push(event_type.event_type_id);
}
}
...
}
onSubmit() {
for (let event_id of this.eventArray) {
this.formData.append('event_type[]', event_id);
}
...
}
onCheckboxChange(e) {
if (e.target.checked) {
this.eventArray.push(e.target.value);
} else {
const index = this.eventArray.indexOf(e.target.value, 0);
if (index > -1) {
this.eventArray.splice(index, 1);
}
}
}
isChecked(eventId){
return this.selectedEventIds.indexOf(eventId)>-1 ? true : null;
}
Now above update code fails if database has values and user does not select any checkbox as it finds eventArray
is empty. If I assign database values to eventArray
in ngOnInit
then onCheckboxChange
event eventArray
shows empty so evenif I deselect checked checkboxes then nothing change in eventArray
in that event.
How I can manage those testcases in angular? Plese guide and help. Thanks in advance.
Aucun commentaire:
Enregistrer un commentaire