I have a set of checkboxes that are generated dynamically. Based on the data, certain checkboxes should be pre-selected. For some reason, ngModel is not achieving this.
Template:
<div *ngFor="let option of options">
<p-checkbox [(ngModel)]="selectedOption"
[value]="option.value"
name="option-row">
</p-checkbox>
</div>
Component:
...
selectedOption!: string | undefined;
getOptions() {
this.apiService.getOptions()
.pipe(
take(1),
tap(() => // logic to check if getOptions() response includes
// an existing value that matches potential options
// (checkboxes)
).subscribe(noop)
}
In the tap()
method, I am checking if a specific value property exists. The code snippet here is a shortened version for demonstration purposes. If it does exist, I assign that value to this.selectedOption
. These values correspond to the checkbox values, but even when this.selectedOption
is set, the checkbox remains unchecked.
In scenarios where the checkbox should be pre-checked, the [(ngModel)]
doesn't seem to capture the updated value of this.selectedOption
.