I have JSON object like this.
{
CR1: "aaa"
CR2: "bbb*2"
CR3: "ccc/2"
CR4: "ddd-23"
CR5: ""
CR6: "SS"
CR7: ""
}
The index after 'CR' is added dynamically and in template when iterated using ngFor it takes view as below:
But when CR index goes above 10 the view changes something like this:
Here is code from template:
<div class="row mt-10" *ngFor="let item of computationLogicObj | keyvalue; trackBy: trackByFn">
<div class="col-md-4">
<label class="form-control-label" for="field_{{item.key}}">{{item.key}}</label>
</div>
<div class="col-md-6">
<input type="text" class="form-control" id="{{item.key}}" name="{{item.key}}" [(ngModel)]="computationLogicObj[item.key]" [disabled]="!isInternal">
</div>
<div class="col-md-2">
<a (click)="deleteComputationLogic(item.key)">
<fa-icon [icon]="'times'"></fa-icon>
</a>
</div>
</div>
and trackByFn
trackByFn(index: any, item: any) {
return item.key;
}
In console the json object is shown like below, which is expected:
{
CR1: "aaa"
CR2: "bbb*2"
CR3: "ccc/2"
CR4: "ddd-23"
CR5: ""
CR6: ""
CR7: ""
CR8: ""
CR9: ""
CR10: ""
CR11: ""
}
What exactly is changing this view then?
keyvalue pipe sorts the keys you provide. as a result 'CR10' < 'CR2' and it appears upper in the list. I suggest keeping your data structure as array of {key: string, value: string} objects and eliminate usage of keyvalue pipe
Related
I have written my get method inside ngOnInIt(). When I am printing data in console it is visible, but when printing in HTML using interpolation, it is returning [ object object]
{{filteredCourses}} ==> [object object]
and when i am using {{course.category|json}} so here i am getting all values of array ["course" : "database" , "category" : "database" , "length" : "2hr" ] thats how the value is coming
html :-
<div class="courses" fxLayout="row wrap" fxLayoutAlign="center" [#animateStagger]="{value:'50'}">
<div class="course" *ngFor="let course of filteredCourses" fxFlex="100" fxFlex.gt-xs="50"
fxFlex.gt-sm="33" [ngClass]="course.category" [#animate]="{value:'*',params:{y:'100%'}}">
<div class="course-content" fxLayout="column" fxFlex="1 1 auto">
<div class="header" fxLayout="row" fxLayoutAlign="center center"
[ngClass]="course.category + '-bg'">
<div class="category" fxFlex>
{{course.category|json}}
</div>
</div>
</div>
Code:
filteredCourses: any[];
this.product_name = getProduct()['name'];
console.log(this.product_name);
this.token = getToken();
this.httpHeaders = new HttpHeaders({ "Authorization": "Bearer " + this.token });
this._httpClient.get('http://127.0.0.1:8000/api/products/info/'+this.product_name+'/',{headers: this.httpHeaders})
.subscribe(
data => {
this.product = data;
this.courses = data['cources'];
this.filteredCourses = this.courses;
console.log(this.filteredCourses);
},
error => {
console.log(error);
}
);
try using JSON.stringify(yourObject) or maybe in certain cases you can use Object.keys().
You need to use loop if its an array of object or you might want to print the properties of object individually.
But if you want to see the object filteredCourses in template, use json pipe.
{{filteredCourses | json}}
In case you need help to print values using *ngFor or properties, do let us know.
I suppose filteredCourses collection contains an array of objects. So you need to iterate through filteredCourses using ngFor directive to render data in the HTML template.
Like:
<ul>
<li ngFor="let item of filteredCourses">{{item.courseName}}</li>
</ul>
I need to get values from json (comes from merged MySQL tables).
I've tried a several solutions from previous topic but none of them worked for me.
access key and value of object using *ngFor
my JSON format is:
[
{
"idemployee":1,
"name":"Ernest",
"surename":"Pająk",
"role":"Obsługa Baru",
"employeehours":[
{
"idemployeehours":1,
"date":"2019-01-10T23:00:00.000+0000",
"quantity":8.0
}
]
}
]
and what I got is "Key: 0 and Value: " (answer from Pardeep Jain topic above)
EDIT:
this is my code:
<div *ngFor="let item of employee| keyvalue">
Key: <b>{{item.key}}</b> and Value: <b>{{item.value}}</b>
employee comes from Angular component and gives mentioned JSON. The problem is getting nested values from "employeehours" (like quantity)
You don't need the keyvalue pipe. employeehours is an array, so you just need a nested *ngFor for the array, so example where you have stored your data in an employees array:
<div *ngFor="let emp of employees">
<p>Name: {{emp.name}} {{emp.surename}}</p>
<div *ngFor="let hour of emp.employeehours">
<p>Date: {{hour.date | date: 'shortDate'}}</p>
<p>Quantity: {{hour.quantity}}</p>
</div>
</div>
DEMO
if you run keyValue pipe on array object you got the keys as the index of the values in the array so tha why you need a nested ngFor to run keyvalue pipe on the value of the array
<div *ngFor="let item of employee">
<div *ngFor="let emp of item |keyvalue ">
Key: <b>{{emp.key}}</b> and Value: <b>{{emp.value}}</b>
</div>
</div>
demo 🔥🔥
UPDATED!
if you want to support sohow keys value of employeehours where the value is array best cases here to create a component to do all of this and use this component to render the new values like recursion
component
export class RenderComponent {
#Input() items = [];
isArray(value) {
return value instanceof Array
}
}
template
<div *ngFor="let item of items">
<div *ngFor="let obj of item | keyvalue " class="well">
Key: <b>{{obj.key}}</b> and Value: <b>{{obj.value}}</b>
<ng-container *ngIf="isArray(obj.value)">
<render [items]="obj.value"></render>
</ng-container>
</div>
</div>
demo 💣💣
Below is my JSON file:
[
{
"Name":"Peter England Shirt",
"Prodimage":["./images/zoom/zoom1hi.jpg","./images/zoom/zoom2hi.jpg","./images/zoom/zoom3hi.jpg"],
"actualPrice":"90",
"discountedPrice":"70",
"desc":"Cotton",
"Prodcolor":["#f1f40e","#adadad","#4EC67F"],
"quantity":[1,3,4,5,60],
"size":["XL","L","M","S"],
"detail":"Take it away",
"sizeChart":["16 waist","Measurements taken from size 30","Model wears size 31. Model is 6'2"],
"shipping":[
{
"type":"Standard",
"days":"5-6 days",
"cost":"200"
},{
"type":"Next day",
"days":"1 days",
"cost":"500"
}
],
"sellerList":[
{
"sellerName":"ABC",
"price":"566",
"deliveryDay":"4-5 working days"
},{
"sellerName":"SEDF",
"price":"300",
"deliveryDay":"4-5 working days"
},{
"sellerName":"QWER",
"price":"555",
"deliveryDay":"2-5 working days"
}
]
}
]
The JS file is as below:
var pJson="./json/product.json";
$http.get(pJson).success(function(response){
$scope.product=response;});
Now, if I want to access "Name" attribute I can call {{product[0].Name}}.
But I am not able to access Prodimage attribute using ng-repeat. I am trying like this:
<div ng-repeat="image in product.Prodimage">
{{image[0]}}
</div>
is this wrong?>
Yes this is wrong ,, note that you have the product object as array ,, so if you want the first object you should do this
<div ng-repeat="image in product[0].Prodimage">
{{image[0]}}
</div>
or if you want to iterate over all the products ,, you need to make a nested ng-repeat
<div ng-repeat="p in product">
<div ng-repeat="image in p.Prodimage">
{{image[0]}}
</div>
</div>
You could loop over it, becasue the outside is technically an array, and use $first for you example of wanting to only grab the first image. You could also use $index but running it through a function that checks the $index.
Fiddle here http://jsfiddle.net/HB7LU/15324/
I just re worked it to loop twice like so
<div ng-repeat="prod in product">
<div ng-repeat="image in prod.Prodimage">
<div ng-show="$first">
{{image}}
</div>
</div>
</div>
then put a div inside the inner repeat that will only show if it's the first item. Again you could change that logic to show by index, or whatever you want. So if you know the index you could change that same logic to this -
see fiddle - http://jsfiddle.net/HB7LU/15332/
<div ng-show="checkIndex($index)"> << or whatever index you want
{{image}}
</div>
and in the controller
$scope.checkIndex = function(item){
if(item === 0){
return true;
}else{
return false;
}
}
You just pass the index of the current item in the repeat and check it. I would recommend this logic over the Prodimage[0] logic so you are not hardcoding it into the html, so if you have to change the desired index, you change it in the controller, not template. The checkIndex is a quick example, you could change that to do whatever you want.
$scope.product[n].Prodimage is an array. So, you need to loop through your product array first, and then loop through the Prodimage array of each product:
<div ng-repeat="prod in product">
<div ng-repeat="image in prod.Prodimage">
{{ image }}
</div>
</div>
Of course, you could also just access the nth image using something like:
<div ng-repeat="prod in product">
{{ prod.Prodimage[0] }}
</div>
Can you change your json to
"Prodimage":[
{ "loc": "./images/zoom/zoom1hi.jpg"},
{ "loc": "./images/zoom/zoom2hi.jpg"},
{ "loc": "./images/zoom/zoom3hi.jpg"}],
then your loop should work
<div ng-repeat="image in product.Prodimage">
{{image.loc}}
</div>
In my Angular app, I am using ng-repeat to cycle through all the items in a JSON object I have. So for example, for my JSON object:
$scope.animals =
{
horse: {
sound: "Nay",
legs: 4,
}
beaver: {
sound: "thwack",
legs: 2
}
}
I want to cycle through to get a list consisting of Horse, Beaveri.e.
<div ng-repeat="(key, value) in animals">
<div class="niceBox">
<h1> {{key}} </h1>
</div>
</div>
but for each animal, I want to have a button that takes the whole object and adds it to a list of my favorite animals. Something like this:
<div ng-repeat="(key, value) in animals">
<div class="niceBox">
<h1> {{key}} </h1>
<div ng-click="addToFavorites(animal)">Add To Favorites</div>
</div>
</div>
The Trouble Is that I can't just pass animal as a parameter since I broke up the ng-repeat into (key, value) already.
How do I reassemble (key, value) so I could use the object as a whole?
Your question is misleading, because there's no original "object" you want to re-assemble - there's just property names and values. If you had a single object for the animal in the first place:
var animals = [{
name: 'horse',
sound: ...,
...
}, {
name: 'beaver',
...
}, ...];
there would be nothing to "re-assemble", you'd just use it:
<div ng-repeat="animal in animals">
{{animal.name}}
<button ng-click="addToFavorites(animal)">...</button>
</div>
Try by this this
<div ng-repeat="(key, value) in animals">
<div class="niceBox">
<h1> {{key}} </h1>
<div ng-click="addToFavorites(key, value)">Add To Favorites</div>
</div>
</div>
And in your controller
$scope.addToFavorites = function(key, value) {
$scope.animal = {};
animal[key] = value;
/** your code **/
}
I am unsure if this has got anything to do with AngularJS at all and if it is only JSON related.
Anyhow, let us say that we have the following JSON:
$scope.dataSets = {
"names": ["Horace", "Slughorn", "Severus", "Snape"],
"genders": ["Male", "Female"]
}
Now, I am using the ng-repeat directive to print the above as follows:
<div ng-repeat="data in dataSets>
//Continue readig to know what I am expcting here
</div>
What I expect within the <div></div> tags is to print "name" and "genders". That is, I wish to print the keys of the JSON. I have no idea what the keys are, as in they could be anything. How can I do this?
As docs state it:
(key, value) in expression – where key and value can be any user defined identifiers, and expression is the scope expression giving the collection to enumerate.
<div ng-repeat="(key, data) in dataSets">
{{key}}
</div>
for accessing Json key-value pair from inside controller in AngularJs.
for(var keyName in $scope.dataSets){
var key=keyName ;
var value= $scope.dataSets[keyName ];
alert(key)
alert(JSON.stringify(value));
}
if dataSets is an array and not an object you first need to ng-repeat the array items and then the key or value.
<div ng-repeat="item in dataSets">
<div ng-repeat="(key, value) in item">
{{key}}
{{value}}
</div>
</div>
just my 2 cents.
For every dataSet in dataSets, print the key and then iterate through the individual items:
<div ng-repeat="(key, dataSet) in dataSets">
<div>{{key}}</div>
<div ng-repeat="value in dataSet">
{{value}}
</div>
</div>
{{dataset}} can be displayed in one go also, the array would be displayed as a comma separated list of values.