extract JSON data in Angular2 - javascript

I have the following JSON output: http://pastebin.com/9bHaBrbX
I would like to make this pseudocode a reality:
For every Model {
For every Year {
For every Style {
if submodel.body is NOT in Array:
load submodel.body to Array;
}
}
}
I would like to store this Array in my model.component so I can use it to make buttons such as:
<button *ngFor="let item in Array" ...> item </button>
How can I extract the data I want (Model[x].Years[y].Style[z].submodel.body) (where x,y,z are variables) from my json response?
I am having trouble conceptualizing how to iterate through nested json objects with JS/TS/Angular2.

Here is a hint :
<div *ngFor="let years of model.years">
<div *ngFor="let year of years">
<div *ngFor="let styles of year.styles">
<div *ngFor="let style of styles">
<!-- your conditions, submodel.body... -->
</div>
</div>
</div>
</div>
Side note: I agree with others above, you should try to write your code yourself.

Use simple http request, it will download the data and store it inside the items variable. Then you can do whatever you want with it - display, sort or just keep.
https://plnkr.co/edit/bU7W6f0aO6eelvyCnKzc?p=preview

Related

Angular show hide with combine condition

I have an array of object need to show hide based on filter like below:
HTML CODE:
Filter:
<div (click)="filter(1)"> F1 </div>
<div (click)="filter(2)"> F2 </div>
<div (click)="filter(3)"> F3 </div>
<div (click)="filter(4)"> F4 </div>
<div *ngFor="let data of datas">
<span *ngIf="data.show">
{{data.name}}
</span>
</div>
ts Code:
this.datas = `[{'name':'product one','filter':'1'},{'name':'product two','filter':'2'},{'name':'product three','filter':'3'},{'name':'product three','filter':'3'},{'name':'product','filter':''},{'name':'product','filter':''},{'name':'product one','filter':'1'},{'name':'product'}]`
filter(query){
this.datas.forEach(function (element, index) {
if (element.filter == query ) {
element.show = true;
} else {
element.show = false;
}
I have tried the above approach it's not working .
Expected like:
By default display all product.
Filter is toggle(on/off)
Need to filter like (F1 & F2 & F3) at the same time like combination
The array objects do not have the show property that you test in the *ngIf directive
Rather simple, really.
I made you a small stackblitz app. But you also really, really need to work on your code. Even as a description for your help, this is just pretty messy.
I didn't code your "Multiple Selections" for you.
https://stackblitz.com/edit/angular-ivy-fbpgdv?file=src/app/app.component.ts
Observation/Suggestions :
Instead of adding a new property show. You can easily achieve that by filtering out the datas array based on the value passed in the filter() method.
Instead of modifying the original array, you can make a deep copy and do the operation on click on filter().
Working Demo : https://jsfiddle.net/srvpw2bo/

images not displaying using array with input and ngFor - Angular

I'm trying to display an array of images via their source link using an ngFor but I am receiving errors and it's not working!
The image HTML code which is within my card component:
<div class="Session-Participants">
<div *ngFor="let image of {{ participantImages }}" >
<img src='{{image}}'/>
</div>
</div>
In the JS file:
#Input() participantImages? = [];
The data is coming from my other component and the html and JS are as below:
<div *ngFor="let sessions of getSortedSessionList()">
<div *ngFor="let session of sessions">
<tl-session-card
[title]="session.name"
[path]="sessionPath(session.id, session.name)"
[participantImages]="getParticipantDetails(session)" // HERE
>
</tl-session-card>
</div>
</div>
the JS:
participantImage = [];
getParticipantDetails(session) {
this.participantImage = session.roles[0].account.thumbnailURL;
return this.participantImage;
}
I'm expecting for the 'this.participantImage' to be returned and then sent to the card component and then broken down to be displayed separately.
I'm sure I am missing something?
Thanks if you can help at all?
Actually in the stackblitz link, you have a proper array and that not reflect perfectly the code you just provide above.
You need to ensure participantImage stay an array otherwise, the ngFor will not work as expected and you will see some errors in your console.
as #prashant-pimpale says, you need to append to the list of participantImage the result.
In the ts file It would be better to use
participantImage = [];
getParticipantDetails(session) {
// ensures this.participanImage keeps its array type and will process all
// other roles
this.participantImage = session.roles.map(account => account.thumbnailURL);
return this.participantImage;
}
Hope it helps
PS: would be better to set the attribute name of participantImage to participantImages since it represent a list of images ;)

How can I show comments of clicked feed only

I'm stuck in a situation, in a nested loop. The top loop iterating over the Feeds array and every feed in Feeds have comments array. This comments is used for inner loop.
My problem is, I have Comment button and on click of that button, I want to show the list of comments only for that feed post. But instead of showing comments on current feed post, it is showing comments for all other feeds also, that's because of use of only one Boolean variable showComments created inside .ts file.
So how can make that work for only the given context Feed post?
HTML
<ng-container *ngFor="let feed of feeds">
<div class="ed-card ed-card-feed">
<div class="ed-card-feed--footer">
<div class="card-feed-values">
<a class="mr-4"><span>{{feed.likes_count}}</span> Likes</a>
<a><span>{{feed.comments_count}}</span> Comments</a>
</div>
<div class="card-feed-actions">
<a class="mr-5" (click)="likePost(feed.id)"><span></span> Like</a>
<span></span> Comment button
</div>
</div>
// Below div needs to be open for that particular feed only
<div *ngIf="showComments" class="ed-card-feed--comments">
<div class="feed-comments-list">
<ng-container *ngFor="let comment of feed.comments?.edges">
<div class="comment-list-item">
<p class="comment-box mt-1">
{{comment.node?.body}}
</p>
</div>
</ng-container>
</div>
</div>
</div>
</ng-container>
P.S. - Please don't confuse with feed.comments?.edges that's just because of GraphQL. It is just an array.
Thanx
You can maintain an array of showComments[] equal to size of feeds with initially set to false. showComments[false,false...]
<ng-container *ngFor="let feed of feeds; let myIndex = index"">
//code here
<span></span> Comment button
//check if true
<div *ngIf="showComments[myindex] === true" class="ed-card-feed--comments">
</ng-container>
Instead of a boolean, you can define a selectedFeeds array:
selectedFeeds = new Array<Feed>();
In the template, you add the feed that has been clicked to selectedFeeds:
<a href="javascript:void(0)" class="mr-5" (click)="selectedFeeds.push(feed)>Comment button</a>
and you filter the comments according to the selected feeds:
<div *ngIf="selectedFeeds.indexOf(feed) >= 0" class="ed-card-feed--comments">
The best way to achieve this is to separate the code to different components. And since each of the component will have it's own instance of comments - you won't have a problem creating a local variable and showing/displaying the comments in there.
I've created an example of how it can be implemented: stackblitz
Another approach
<ng-container *ngFor="let feed of feeds">
Comment button
<div *ngIf="feed.showComments" class="ed-card-feed--comments">
</ng-container>
Js file
toggleComments(feed) {
feed.showComments = true // (feed.showComments = !feed.showComments => to show or hide (toggle))
}

If all array items are hidden show another div in AngularJS

I'm using ng-repeat on my page. ng-class working very well.
<div class="card news" ng-repeat="item in news track by $index" id="{{news.nid}}" ng-init="parentIndex = $index" ng-class="{hidden: '{{getCheck($index)}}' == 'true'}">
...
</div>
Now I need, if all items are hidden, show this div:
<h3 class="news-empty">No news</h3>
Whats the rules? How can I do it? Thanks.
You need another method that checks if all elements are hidden:
$scope.everythingIsHidden = function() {
return $scope.news.every((new, index) => $scope.getCheck(index));
}
$scope.getCheck = function(index) { // Your getChek function that I suppose it checks if an element is hidden based on index
//...
}
<h3 class="news-empty" ng-if="everythingIsHidden()">No news</h3>
TheCog's answer will work. If you want to do this in a more 'Angular' way you're going to need to refactor what you have.
You shouldn't be trying to hide them with a CSS class. ngRepeats have a built in filter syntax. So, you should be filtering them out.
<div class="card news"
ng-repeat="item in news | filterMethod as results track by $index"
id="{{news.nid}}"
ng-init="parentIndex = $index"
>
<h3 class="news-empty" ng-if="results.length === 0" >No news</h3>
The as results statement in the repeat will store the filtered array in results. filterMethodneeds to be an angular filter and it will probably work similarly to your getCheck($index) method.
You want to add an ngShow to the h3 tag, and aim it at a function you write in your controller that checks if the array is empty, probably by iterating over the same array that's hidden and running getCheck($index) on each.

track by $index isn't solving dupes error

I am trying to iterate through an array of objects and display them in my HTML using Angular. I have done this before without any problems by using "track by $index". But the standard error is still raised:
Error:
[ngRepeat:dupes] http://errors.angularjs.org/1.3.15/ngRepeat/dupes?p0=(key%2C%20value)%20in%20n&p1=string%3Ab&p2=b
But I have already added track by $index. I am confident there isn't any issue requesting the data as I have been able to display it correctly.
<div ng-repeat="n in post.userData.bookmarks track by $index" >
<div ng-repeat="(key, value) in n">
<div>{{ key }}</div>
</div>
</div>
Suggestions?
Dataset:
bookmarks: [{"1234": "Title1"}, {"5678": "Title2"}]
What happens is that a user bookmarks a post that they want to read later. I save the post id and the title of the post to an object and store this in an array. (I actually just wanted to store it to an object like so: {"1234": "Title1", "5678": "Title2"}, but couldn't figure it out with mongodb, since it doesn't seem to let you save as object data type.)
Then I want to ng-repeat the user's bookmarks in their profile. The only way I know how to do this is to iterate through the array and then iterate through each object. Of course, there is only one item in each object. But this is why I have the second ng-repeat. But when I do track by $index for both, as one of the answers lists below, it still doesn't give the desired behavior.
Something that could be causing a problem is that I also have a sort of dashboard that can be viewed on the side while viewing any given post. And on the dashboard they should be able to see their bookmarks. Also if they are on a post that they have bookmarked, if they click a (un)bookmark button on the post, it should automatically remove that bookmark on their bookmark dashboard.
But none of the suggestions have worked.
You forgot another ng-repeat: <div ng-repeat="(key, value) in n track by $index">
I don't know Why u write two times repeat
<div ng-repeat="n in post.userData.bookmarks track by $index" >
<a ng-href="/tuts/{{n.key}}">{{ n.key}}</a>
</div>
OR
<div ng-repeat="(key,value) in post.userData.bookmarks track by $index" >
<a ng-href="/tuts/{{value}}">{{ value}}</a>
</div>
key is anything which you get from object.

Categories

Resources