Issue
I am using the method compareEntity to compare 2 option objects with ngValue to indicate the selected one. However, the second argument of compareEntity is always an empty string, why? What am I doing wrong?
I am using angular 12.
The code: Used to set the selected object:
ngOnInit() {
this.audits$ = this.auditService.entities$.pipe(
withLatestFrom(this.entity$),
map(([audits, entity]) => {
if (this.formGroup && entity.audit) {
this.formGroup.value.audit = audits.find((a: Audit) => a.id === entity.audit);
this.logger.debug(`Setting the initial audit value of audit with id: [${this.formGroup.value.audit?.id}]`);
}
return audits;
})
);
}
The compare method:
compareEntity(o1: any, o2: any): boolean {
return o1?.id === o2?.id;
}
And the piece of HTML:
<label for="audit">My label</label>
<select formControlName="audit" id="audit" [compareWith]="compareEntity">
<option value="null" disabled selected>Select something</option>
<option *ngFor="let audit of audits$ | async; trackBy: trackById" [ngValue]="audit">
{{audit.name}}
</option>
</select>
</div>
Solution
You've no selected audit in your form, so it compares the options with the currently selected value, in your case null.
So null as o2 is correct.
Check this stackblitz as a simplified sample of your code where you can see it more easily. Uncomment this.selectedAudit
in the ngOnInit, and you'll see the results with a predefined audit selection.
If this isn't the full solution, validate if your form is setting your audit correctly on selection
--- edit: ---
Try setting your form with:
this.formGroup.patchValue({
audit: audits.find((a: Audit) => a.id === entity.audit);
})
Or as mentioned by Gurkan Yesilyurt
this.formGroup.get('audit').setValue(audits.find((a: Audit) => a.id === entity.audit));
I've update the stackblitz, if you uncomment line 37: this.displayAudit(this.auditArray[1]);
this will use a preselected audit. In line 46 you'll see me use patchValue on the form with that audit obj
Answered By - James D
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.