I have a situation where I receive an object of data from my database that contains records for versions of a file. There could be 5 versions (5 records) or a single version returned.
My issue is that I am using ngFor
to loop over the array of data and print them to the table. In the event that there is only a single record returned, the data is no longer an array of objects and is just a single object.
<tbody class="ruleVersions">
<tr *ngFor="let m of mapData.ruleVersion.x">
<td class="small">V {{ m.RuleVersion }}.0</td>
<td [innerHtml]="m.CreatorNTID | ntidLink"></td>
<td class="small">{{ m.VersionNotes ? m.VersionNotes : 'N/A' }}</td>
<td class="small">{{ m.BasedOnRuleVersionID ? m.BasedOnRuleVersionID : 'N/A' }}</td>
<td class="small">{{ m.MetaInsertUtc }}</td>
</tr>
</tbody>
Multiple Records:
Single Record:
This poses a problem because the ngFor
is set up to loop over arrays. Due to the single record not being an array of objects like when there are multiple, it throws this error:
Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
What is the best way to solve for this? Is there anything in angular I can use to treat the data as an array even if its not, perhaps with a pipe of some sort?
The only other way I can think of is passing the entire object through a function and having it push objects into arrays if its a single record. That then poses the problem of not wanting every single record to be an array.
Just curious if there are any built in angular ways to solve for this?
Update:
I solved this by creating a pipe.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'isArray' })
export class IsArrayPipe implements PipeTransform {
transform(x): any {
return Array.isArray(x) ? x : [x];
}
}
<tr *ngFor="let m of mapData.ruleVersion.x | isArray: x">