I have a json object(items) and I am iterating through ngFor. I need to assign index value to variable i only if it matches the condition item.isRepetable==true Is there any way I can assign the index value to variable i in *ngFor on condition matches
<ul *ngFor="let item of items;let i=item.isRepetable?index:0">
<li>{{item}}</li>
</ul>
Create and apply a filter pipe, then you don't need a condition and the index will match.
<ul *ngFor="let item of items | isRepeatableFilter;let i=index">
<li>{{item}}</li>
</ul>
There is no way to modify the index generated by *ngFor
Related
Using Angular 2, I want to duplicate a line in a template multiple times. Iterating over an object is easy, *ngFor="let object of objects". However, I want to run a simple for loop, not a foreach loop. Something like (pseudo-code):
{for i = 0; i < 5; i++}
<li>Something</li>
{endfor}
How would I do this?
You could dynamically generate an array of however time you wanted to render <li>Something</li>, and then do ngFor over that collection. Also you could take use of index of current element too.
Markup
<ul>
<li *ngFor="let item of createRange(5); let currentElementIndex=index+1">
{{currentElementIndex}} Something
</li>
</ul>
Code
createRange(number){
// return new Array(number);
return new Array(number).fill(0)
.map((n, index) => index + 1);
}
Demo Here
Under the hood angular de-sugared this *ngFor syntax to ng-template version.
<ul>
<ng-template ngFor let-item [ngForOf]="createRange(5)" let-currentElementIndex="(index + 1)" [ngForTrackBy]="trackByFn">
{{currentElementIndex}} Something
</ng-template>
</ul>
You can instantiate an empty array with a given number of entries if you pass an int to the Array constructor and then iterate over it via ngFor.
In your component code :
export class ForLoop {
fakeArray = new Array(12);
}
In your template :
<ul>
<li *ngFor="let a of fakeArray; let index = index">Something {{ index }}</li>
</ul>
The index properties give you the iteration number.
Live version
Depending on the length of the wanted loop, maybe even a more "template-driven" solution:
<ul>
<li *ngFor="let index of [0,1,2,3,4,5]">
{{ index }}
</li>
</ul>
You can do both in one if you use index
<div *ngFor="let item of items; let myIndex = index>
{{myIndex}}
</div>
With this you can get the best of both worlds.
The better way to do this is creating a fake array in component:
In Component:
fakeArray = new Array(12);
InTemplate:
<ng-container *ngFor = "let n of fakeArray">
MyCONTENT
</ng-container>
Plunkr here
you can use _.range([optional] start, end). It creates a new Minified list containing an interval of numbers from start (inclusive) until the end (exclusive). Here I am using lodash.js ._range() method.
Example:
CODE
var dayOfMonth = _.range(1,32); // It creates a new list from 1 to 31.
//HTML Now, you can use it in For loop
<div *ngFor="let day of dayOfMonth">{{day}}</div>
The best answer for this question I have found here
You need to create an attribute inside your class and reference it to Array object:
export class SomeComponent {
Arr = Array; //Array type captured in a variable
num:number = 20;
}
And inside your HTML you can use:
<ul id="next-pages">
<li class="line" *ngFor="let _ of Arr(10)"> </li>
</ul>
queNumMin = 23;
queNumMax= 26;
result = 0;
for (let index = this.queNumMin; index <= this.queNumMax; index++) {
this.result = index
console.log( this.result);
}
Range min and max number
for Example let say you have an array called myArray if you want to iterate over it
<ul>
<li *ngFor="let array of myArray; let i = index">{{i}} {{array}}</li>
</ul>
If you want to use the object of ith term and input it to another component in each iteration then:
<table class="table table-striped table-hover">
<tr>
<th> Blogs </th>
</tr>
<tr *ngFor="let blogEl of blogs">
<app-blog-item [blog]="blogEl"> </app-blog-item>
</tr>
</table>
If you want duplicate lines multiple time.
You can simply do :-
declare in .ts file
public repeater = "<li>Something</li>";
Then use following to print it .html file.
{{repeater.repeat(5)}}
My object has a specific set of key / value pairs,
i want to get a specific value, not everything, how can i do this?
For example:
.ts
movie = {
title:'title',
description:'descriprtion',
rating:4
};
html:
<ul *ngFor="let item of movie | keyvalue">
<li> {{item.value}} </li>
</ul>
And I only want to receive item.description, can you tell me how this can be implemented?
<ul *ngFor="let item of movie | keyvalue">
<ng-container *ngIf="item.key === 'description'">
<li>{{item.value}}</li>
</ng-container>
</ul>
But to be honest you would be better off just doing:
<div>{{ move.description }}</div>
Since you do not seem to want to iterate the object props, but only want description.
I have a list like this
<ul>
<li *ngFor="let product of items.Products| slice 0:3 ; let i = index">
{{ product?.ProductsDescription}}
<li>
</ul>
All i want i to is, display a list of products, but i wan't to limit the exibition to only 3 products, and below, in another <li></li> display "And more {{ quantity-left-of-products }}"
Example:
I Have 6 products, so it would display:
Item 1
Item 2
Item 3
And more 3
Something like this:
In my knowledge i would have to find a way to access the index property outside the ngFor.
Can anyone help me?
You can achieve what you want without accessing the index value outside the context.
Create a variable in TS to use it as a parameter in the slice pipe.
sliceValue = 3;
loadMore() {
this.sliceValue = items.Products.length;
}
Template:
<ul>
<li *ngFor="let product of items.Products| slice 0:sliceValue ; let i = index">
{{ product?.ProductsDescription}}
<li>
<li (click)="loadMore()" *ngIf="items.Products.length > sliceValue">And more {{items.Products.length - sliceValue}}</li>
</ul>
Use *ngIf for displaying the "And More" when necessary. When the user clicks on "And More" the <li> for "And More: hides and the rest of the list loads.
I can access my desired field from a JSON object like so:
<li ng-repeat='customer in customers[0][data]["DisplayName"] | filter:search'>{{ customer }}</li>
However, that only returns one object's property.
Using AngularJS, is there a way to loop through the following?
customers[0][data]["DisplayName"]
customers[1][data]["DisplayName"]
customers[2][data]["DisplayName"]
customers[3][data]["DisplayName"]
customers[4][data]["DisplayName"]
...
customers is an array, so by doing ng-repeat you will already loop through it. But I think what you want is either: 1) show the DisplayName property inside <li> or 2) filter by DisplayName.
To show the nested property, do the following
<li ng-repeat="customer in customers">
{{ customer[data]["DisplayName"] }}
</li>
To filter on nested property, for example on DisplayName:
<li ng-repeat="customer in customers | filter:{data: {DisplayName: search}}">
...
</li>
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.