How to get attributes of nested object with ngFor - html

I am trying to show the value of "type" in ngFor table but I was getting object '[object Object]' of type 'object'.
NgFor only supports binding to Iterables such as Arrays.**
json
[{
"id": 123,
"name": "Paul",
"cars":
{
"type": "toyota",
"year": "2013"
}
},
{
"id": 126,
"name": "Frank"
},
{
"id": 125,
"name": "Joy",
"cars":
{
"type": "bwm",
"year": "2000"
}
},
{
"id": 133,
"name": "Bob"
}]
html
//....
<tr *ngFor="let info of information;">
<td>{{info.name}}</td>
<td *ngFor="let info2 of info.cars;"> //I want to loop through and get the type value of cars
<td>{{info2.type}}</td>
</td>
<td><button type="button" (click)="showDetail()">View</button></td>
</tr>
//...
Some object has cars, how to I get the type value in the table? Another area I would need help is, how to show the "type" value (for object that has cars attribute) on a input field when "View" button is clicked. Below is my .ts file where I need to grab the type value:
comp.ts
//....
information = [];
carsType= {}; to hold type value for objects that has it
showDetail(data: any) {
this.formData.controls.name.setValue( data.name );
// how do I get cars "type" value for each object
}

Try like this:
Working Demo
<table border="1">
<tr *ngFor="let info of information;">
<td>{{info.name}}</td>
<td>{{info.cars?.type}}</td>
<td><button type="button" (click)="carType = info.cars?.type">View</button></td>
</tr>
</table>
<input type="text" [(ngModel)]="carType"/>

Try this
<tr *ngFor="let info of information;">
<td>{{info.name}}</td>
<td>{{info?.cars?.type}}</td>
<td><button type="button" (click)="showDetail()">View</button></td>
</tr>

Related

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor Angular 9

I tried so many solutions none of them are not working. please help me to solve this. I need to loop through JSON objects. below is what I tried and my JSON code. I can print the Section name in tr tag but I cannot print the School object Name in the tr tag.
service.ts
getSections(): Observable<Section> {
return this.http
.get<Section>(this.apiUrl + 'sections/all')
.pipe(
retry(2),
catchError(this.handleError),
);
}
Component.ts
getSections() {
this.service.getSections().subscribe(response => {
Object.assign(this.sectionData, response);
console.log(response);
});
}
component.html
<table class="table table-hover">
<thead class="thead-light">
<tr>
<th>#</th>
<th>Section Name</th>
<th>School Name</th>
</tr>
</thead>
<tr *ngFor="let pro of sectionData ;let i=index">
<td [hidden]="true">{{pro.sectionID}}</td>
<td>{{i + 1}}</td>
<td>{{pro.Name}}</td>
<ng-container *ngFor="let sch of pro.School">
<td>{{sch.Name}}</td>
</ng-container>
</tr>
</table>
My JSON
[{
"$id": "1",
"SectionID": 1,
"SchoolID": 6,
"Name": "Grade 1",
"Active": true,
"Tstamp": null,
"Classes": [],
"School": {
"$id": "2",
"SchoolID": 6,
"Name": "Yalpanam",
"AlternativeName": "سصر ءصيص",
"TelephoneNumber": "16556489",
"URL": "",
"EmailID": "",
"Longitude": null,
"Latitude": null,
"Active": true,
"Tstamp": null,
"ClassSections": [],
"NonStaffs": [],
"Principals": [],
"Students": []
}
}]
The error which I get is
Error Msg
In you JSON, School is not an array - it is an object. So you can't iterate over it. To fix that, in your markup change:
<ng-container *ngFor="let sch of pro.School">
<td>{{sch.Name}}</td>
</ng-container>
to simply
<td>{{pro.School?.Name}}</td>

iterating a json array in angular

I have a Json string which looks like below.
{
"testdata": [{
"id": 1,
"name": "testname1 ",
"description": "test description1"
},
{
"id": 2,
"name": "testname2 ",
"description": "test description2"
},
{
"id": 3,
"name": "testname3 ",
"description": "test description3"
}
],
"dummydata": [{
"category": "Test with dummy data",
"testdata": [{
"id": 5,
"name": "testname1",
"description": "test description1."
}],
"testnos": 12,
"testresult": "success"
},
{
"category": "Test with original data",
"testdata": [{
"id": 7,
"name": "testname3",
"description": "test description3."
}],
"testnos": 19,
"testresult": "success"
}
],
"valueofcoding": 22,
"valueoftesting": 21,
"valueofbugfix": 6
}
This how I get the json response in my angular class. I am not sure how to show the values in the html using angular.
<tr *ngFor="let data of dataArray">
<td class="my-table-header"><span class="badge badge-light">Values</span></td>
<td class="cntr"><input type="text" readonly class="form-control-plaintext my-table-header-val" value="{{data.valueofcoding}}"/></td>
<td class="cntr"><input type="text" readonly class="form-control-plaintext my-table-header-val" value="{{data.valueoftesting}}"/></td>
<tr>
valueofCoding and valueoftesting are not part of the array of array. So I did like above but I am getting below error.
ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
I have seen some of the post which is giving same sort of error. But this json format is entirely different and complex. Please help me to sort out this .
dataArray is an Object and *ngFor with is used for the array so if you want to iterate loop over the object in html you can use *ngFor with keyvalue pipe so you can try like this.
<tr *ngFor="let data of dataArray | keyvalue">
<td class="my-table-header"><span class="badge badge-light">Values</span></td>
<td class="cntr" *ngIf="data.key === 'valueofcoding'"><input type="text" readonly class="form-control-plaintext my-table-header-val" value="{{data.value}}"/></td>
<td class="cntr" *ngIf="data.key === 'valueoftesting'"><input type="text" readonly class="form-control-plaintext my-table-header-val" value="{{data.value}}"/></td>
<tr>

How to Fetch Data from JSON multiple array(live data from DB) using observable in Angular2

JSON response is as below:
{
"clientInfo": [
{
"clientId": "1234",
"clientName": "Test1234"
},
{
"clientId": "4356",
"clientName": "Test4356"
}],
"realTimeClientInfo": [
{
"clientId": "1234",
"clientName": "Test1234",
"Location": "Test1234",
"Designation" :"Test1234"
},
{
"clientId": "4356",
"clientName": "Test7896",
"Location": "Test7896",
"Designation" :"Test7896"
}]
}
I want to fetch the data from the second JSON array.
In client.component.ts invoke the clientService as below:
#Input() clientInfo$: Observable<any>;
constructor(private clientService: ClientService) { }
ngOnInit() { this.clientInfo$ = Observable
.interval(1000)
.startWith(0).switchMap(() =>
this.clientService.getAllInfo()); }
client.service.ts is as below :
getAllInfo(): Observable<ClientInfo[]> {
this.http.get<ClientInfo[]>('http://localhost:8080/api/auth/clientInfo');
In client.component.html
<table class="table table-hover">
<thead>
<tr>
<th *ngFor="let col of clientH">{{ col }}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let client of clientInfo$ | async ">
<td *ngFor="let col of clientH"> {{client [col]}}</td>
</tr>
</tbody>
</table>
If the JSON contains only one single array this is working. How we can use the same logic to retrieve some values from first array and some other values from the second array

access value in array from Json response angular 4

i wanna display a field in array at table .. how can i access SubjectCode in my Json Response using angular 4 ? .. My code give me error [Error trying to diff '[object Object]'. Only arrays and iterables are allowed]
Json Response :
{
"$id": "1",
"Council_ID": 88,
"place": "bla bla",
"number": "45",
"type": 1,
"date": "2017-11-08T00:00:00",
"time": "04:51",
"user_Id": 15,
"subjects": [
{
"$id": "2",
"subjectCode": "45",
"type": 1,
"faculty": "medicine",
"branch": "اسكندرية",
"gender": true
}
],
"absence": []
}
meeting.component.html:
<table class="table table-hover table-condensed text-center">
<tbody>
<tr *ngFor="let subject of subjectsWithID">
<td > {{subject.subjects.subjectCode}} </td>
</tr>
</tbody>
</table>
meeting.component.ts:
this.dataStorageService.getCouncilId(this.meetingID).subscribe(response => {
this.subjectsWithID = response.json();
console.log(this.subjectsWithID, 'all Json Resopnse Here')
});
You should use ngFor over subjects, code should be,
<tr *ngFor="let subject of subjectsWithID.subjects">
<td > {{subject.subjectCode}} </td>
</tr>
Your subjects property is an array. If you want to display it, then you should do
{{subject.subjects[0].subjectCode}}

Creating a table header(th) and body(td) from json in angular app

I have an angular app where i am trying to create a table from a json. My json is as follows:
[
{
"campus_id": "321",
"name": "0"
},
{
"campus_id": "231",
"name": "1"
},
{
"campus_id": "123",
"name": "2"
}
]
Generally we will create a table in the html as follows:
<table class="table table-striped">
<tr>
<th>
Campus id
</th>
<th>
Name
</th>
</tr>
<tr ng-repeat="item in items">
<td >
{{item.campus_id}}
</td>
<td >
{{item.name}}
</td>
</tr>
</table>
How do i create even the headers from the json instead of defining them ourselves?
I would add the column headers within the json result like so
columnDefs: [
{field: 'campus_id', displayName: 'Campus ID'},
{field: 'name', displayName: 'Name'}],
data:
[
{
"campus_id": "57911000",
"name": "0"
},
{
"campus_id": "57911001",
"name": "HIGHLAND PARK HIGH SCHOOL"
},
{
"campus_id": "57911007",
"name": "P A S S Learning Center School"
}
]
otherwise you could use the key, value pairing ng-repeat="(key,value) in items" with a filter to return 1 row and then use {{key}}