I have implemented several modal windows that allow users to select records from a paged list in the database. For example, there is a component called course.select.component.ts
specifically for selecting courses.
The modal window accepts an @Input() multiple: boolean
property which determines whether it should return a single course or multiple courses. The emitter function is defined as:
@Output() courseChange = new EventEmitter<Course | Course[]>();
In some instances, I can bind the selection to a property (Course) in the model, while in others I enable users to select multiple courses.
Everything was functioning smoothly until I encountered an error message after upgrading AngularCLI:
Type 'Course | Course[]' is not assignable to type 'Course'
This error occurs when I bind the selector like this:
<course-selector [(course)]="training.course" multiple="false" />
I understand that `training.course` must be a singular course. However, the selector component does not inherently know that it will always be a singular value, causing the issue.
Interestingly, the components also return the ID of the selected course(s) via the ngModel
. Therefore, the complete HTML looks like this:
<course-selector [(course)]="training.course" multiple="false" [(ngModel)]="training.courseId" />
And in the code:
writeValue(courseId: string | string[]): void {
if (courseId !== undefined) {
this.courseId = courseId;
this.propagateChange(this.courseId);
}
}
In essence, `training.courseId` is expected to be a string, but the returned value could potentially be a `string | string[]`. Surprisingly, the compiler does not raise any alarms about this discrepancy in production mode (--prod).
Is there a simple workaround to address this issue without having to rewrite all my components?