loop through array or json file in angular 4 - arrays

I want to loop through an array of objects in angular 4 , I use a .ts file to export array as a variable in posts.ts
export var posts = [
{
"name":"art",
"title":"Art",
"items":[
{
"id": "1",
"title":"Tooling Up",
"author":"Amber Bravo",
"date":"June 14 2015",
"primaryColor":"#5a7785",
"secondaryColor":"#455a64",
"image":"https://g-design.storage.googleapis.com/production/v5/assets/tooling-up-header-a13cfd9a.svg",
"desc":"How a new generation of prototyping tools at Google will help designers build better software.",
"content":"# content goes here"
},
{
"id": "2",
"title":"Expressing Brand in Material",
"author":"Viktor Persson & Rachel Been",
"date":"July 4 2015",
"primaryColor":"#202226",
"secondaryColor":"#333",
"image":"https://g-design.storage.googleapis.com/production/v5/assets/article_brand_2x1_202226-fc539618.svg",
"desc":"Material design offers a system for designing functional and elegant software. How does your brand fit into the framework? We’ve created a step-by-step guide to staying on-brand while going material.",
"content":"# content goes here"
},
{
"id": "3",
"title":"New Design Tools",
"author":"Amber Bravo",
"date":"July 29 2015",
"primaryColor":"#3e50b4",
"secondaryColor":"#303fc3",
"image":"https://g-design.storage.googleapis.com/production/v5/assets/150727_GD_Article_ToolingUpFurther_1x1Tile-01-86c8e03e.svg",
"desc":"See Also: (More) thoughts on design tools",
"content":"# content goes here"
}
]
},
{
"name":"film",
"title":"Film",
"items":[
{
"id": "1",
"title":"Design from iOS to Android (and Back Again)",
"author":"Roman Nurik & Viltor Persson",
"date":"Aug 20 2015",
"primaryColor":"#3e50b4",
"secondaryColor":"#303F9F",
"image":"https://g-design.storage.googleapis.com/production/v5/assets/renditions/Article_iOS_to_Android_Header_3e50b4-f064882f-1240.png",
"desc":"A practical guide to designing across platforms",
"content":"# content goes here"
},
{
"id": "2",
"title":"Demystifying Density",
"author":"Sebastien Gabriel",
"date":"July 10 2015",
"primaryColor":"#00ccb8",
"secondaryColor":"#00b7a5",
"image":"https://g-design.storage.googleapis.com/production/v5/assets/article_dpi_00ccb8-34fdd39e.svg",
"desc":"Sebastien Gabriel takes one for the team with his exhaustive guide to DPI & PPI",
"content":"# content goes here"
},
{
"id": "3",
"title":"Pixate and Form 1.3",
"author":"Google Design",
"date":"May 30 2015",
"primaryColor":"#eeeeee",
"secondaryColor":"#9e9e9e",
"image":"https://g-design.storage.googleapis.com/production/v5/assets/pixate-and-form-1-3-header-2061f19f.svg",
"desc":"Discover the latest features and start designing native prototypes on your device.",
"content":"# content goes here"
},
{
"id": "4",
"title":"Welcome to the New Google Design",
"author":"Google Design",
"date":"Sep 10 2015",
"primaryColor":"#3367d6",
"secondaryColor":"#2755CC",
"image":"https://g-design.storage.googleapis.com/production/v5/assets/Article_Welcome_Header_2880-ce3ec22d.svg",
"desc":"More design, all the time",
"content":" # content goes here"
}
]
},
{
"name":"photography",
"title":"Photography",
"items":[]
},
{
"name":"design",
"title":"Design",
"items":[]
},
{
"name":"topten",
"title":"Top Ten",
"items":[]
},
{
"name":"aday",
"title":"A Day in the Life",
"items":[]
}
]
then I import it in app.componenet.ts normally with :
import { posts } from './posts';
now what I don't know is how to loop through it or how to load json file then loop through it I mean how to loop in html to display data inside the app.componenet.html

You have to pass this array to view.
#Component(...)
class AppComponent {
posts = posts;
...
And then in view you have to use *ngFor directive.
<ng-container *ngFor="let post of posts">
{{ post.title }}
</ng-container>

Related

Display categories from API instead of writing manually in ReactJS

I have created a ReactJS application which can display the data of a restaurant menu from an API and it is working properly.
I have added a function to filter the data with left menu according to the category (for example if I want to see only items with category Pizza items I will click on Pizza, if I want to view only items with category Juices then on Juices).
So what I have done for my left menu is that I have written down all the categories and made use of a function to filter the data which makes me change the left menu whenever the API categories change.
Now I want to get the categories list in the left menu from my API so that I don't need to change the left menu every time I change the API.
How can I make changes in my code based on the requirement I have so that I can achieve the functionality I want.
My API data is in this way:
[
{
"Name": "Chicken pizza",
"Category": "Pizza",
"Type": "non-veg",
"Price": 376,
"id": "1"
},
{
"Name": "Paneer Cheese Pizza",
"Category": "Pizza",
"Type": "veg",
"Price": 350,
"id": "2"
},{
"Name": "Orange Juice",
"Category": "Juices",
"Type": "veg",
"Price": 45,
"id": "3"
},
{
"Name": "Badam Fruit Mix",
"Category": "Juices",
"Type": "veg",
"Price": 50,
"id": "4"
},
{
"Name": "Vanilla Icecream",
"Category": "Ice Creams",
"Type": "veg",
"Price": 50,
"id": "5"
}
]
Now the functionality I added to filter data using the side menu is this:
const filterItem = (category) =>{
const updatedItems = mainArray.filter((curcategory)=>{
return curcategory.Category === category;
})
setData(updatedItems);
}
<ul>
<li onClick={()=>setData(mainArray)}>All</li>
<li onClick={()=>filterItem("Pizza")}>Pizza</li>
<li onClick={()=>filterItem("Bread")}>Bread</li>
<li onClick={()=>filterItem("Shakes")}>Shakes</li>
<li onClick={()=>filterItem("Ice-Cream")}>Ice Cream</li>
<li onClick={()=>filterItem("Cakes")}>Cakes</li>
<li onClick={()=>filterItem("Juices")}>Juices</li>
</ul>
From here what are the I have to make so that I can display the categories of the items from API without the need to write it down myself.
I have created an array in this way for the categories:
const allCategory = ["All", ...new Set(filteredData.map((curElem)=> curElem.Category ))];
console.log(allCategory);
Now what are things I have to implement to achieve the functionality so that I can display the categories of the API in the left menu in my application. Guide me with whatever the knowledge you have which can help me overcome this problem and find the solution I'm searching for.
I'll give my sandbox link of my application for clear understanding of my code.
https://codesandbox.io/s/qr-menu-smvr6h?file=/src/App.js
I want to change my left menu from hardcoding and get the categories list from API.

Best way to store presentation-specific data in react-redux application

I know the best practice is not using a redux store to save any kind of visualization-related data. But I don't see any way to avoid that in my project. I have a simple store like this:
{
pages: {
byId: {
'0': {
id: '0',
canvases: {
byId: {
'0': {
id: '0',
layers:
{
byId: ['0':{uid:'0'}],
allIds: ['0']
}
}
},
allIds: ['0']
},
selectedId: '0'
}
},
allIds: ['0']
}
}
It just stores the document filled by pages. Each page may have one or more canvases. Each canvas has zero or more layers. Visually each page/canvas/layer is a tree of nested blocks. My idea is putting a selection frame with some handles on top of z-index of my HTML when user clicks onto a layer. The problem is that selection component is in a different DOM tree relatively to the page but at the same time I need to know a bounding rectangle of my page, canvas and layer to overlay the selection correctly. What is the best way to do that? Do I need to use a redux store to save my bounding area?
I think a good solution here will be normalizr. It takes a json like this:
{
"id": "123",
"author": {
"id": "1",
"name": "Paul"
},
"title": "My awesome blog post",
"comments": [
{
"id": "324",
"commenter": {
"id": "2",
"name": "Nicole"
}
}
]
}
and turns it into something like this:
{
result: "123",
entities: {
"articles": {
"123": {
id: "123",
author: "1",
title: "My awesome blog post",
comments: [ "324" ]
}
},
"users": {
"1": { "id": "1", "name": "Paul" },
"2": { "id": "2", "name": "Nicole" }
},
"comments": {
"324": { id: "324", "commenter": "2" }
}
}
}
Take a look at the docs for normalizr, I think it can help you.
I decided to choose MobX + MST framework: https://github.com/mobxjs. This one is covering snapshots to easily manage application states. I am even able to connect Redux Dev Tools to track my state at runtime. In addition to that it has a support of volatile states which makes sense for storing some temporary data like drag and drop mouse offset or some not tied to store visual data. And another one thing is that undo/redo logic can be implemented easily. I am originally from OOP world so MobX/MST is closer to my mindset than Flux/Redux concepts.

JSON data comparison in Angularjs

I am doing a college project. In category page there will be product categories coming from json-
[{
"code": "mc",
"name": "Mobile",
"desc": "We provide range of latest mobile phones with best price in the market",
"imageUrl": "images/mobile.jpg"
},
{
"code": "lc",
"name": "Laptops",
"desc": "Huge sale is going on Lenova,HP and Apple's laptop",
"imageUrl": "images/lappy.jpg"
},
{
"code": "ic",
"name": "ipads",
"desc": "ipad mini is available with the cheapest price.Go grab the offer",
"imageUrl": "images/ipad.jpg"
},
{
"code": "sc",
"name": "Storage Devices",
"desc": "All kind of storage devices are available here",
"imageUrl": "images/storage.jpg"
}
]
As the category list is dynamic for eg 4, trying to build up link to list page depends on the category based on code data in JSON. For example if click on mobile in category.html, result.html will be mobile list, if iPad then iPad list. Right now category page done and trying to pass and receive code in JSON to compare in condition to display concerned data like laptop or desktop.
Present js is:
var catApp = angular.module("catApp", ["ngStorage"]);
catApp.controller('CountryCtrl', function ($scope, $http, $localStorage){
$http.get('categories.json').success(function(data) {
$scope.categories = data;
});
$scope.save = function() {
window.location.replace('result.html');
$scope.type=categories;
if(type.code=='mc'){
localStorage.setItem('msg1', 'Mobiles');
}
$scope.data1 = localStorage.getItem('msg1');
});
to display it on result.html-
<body ng-app="catApp">
<div ng-controller="CountryCtrl">
{{data1}}
</div>
</body>
Please help me to display product name in result.html comparing the 'code' from the json.
In short want to display category name in result.html depends on which category user click where category also dynamic coming from json with a fag value code to make it work like-
freshtechsample.tk/pal/test.html
Only difference is in above html links are static, in required page links are dynamic.
Present output:http://freshtechsample.tk/pal/category.html

How do I get and set model data that's nested deep in Backbone?

I have this model and I want to update the team value when I gather the correct info on a form submit but I'm not sure how to the specific team. I know in backbone I can use the model to get teams but I'm not sure how to then go from teams into the correct team using the code attribute?
I've tried:
// My new team to replace team in code EFU"
var newTeam: {
"id": "POS-876",
"name: "Swansea City"
}
var teams = this.model.get('teams');
var selectedTeam = teams.get('EFU'); // I know this is wrong
selectedTeam.set('team', newTeam);
I'm not sure how I target the correct team then update the team details?
Model
{
"id": "4V6",
"name": "Premier League",
"teams": [{
"code": "EFU",
"team": {
"id": "POS-1",
"name": "Manchester United"
}
}, {
"code": "BMD",
"team": {
"id": "POS-223",
"name": "Chelsea"
}
}]
}
Your Model is a bit confusing. Why is it wrapped in array brackets? And why are you getting 'exchanges' instead of 'teams'? And should perhaps teams be a collection instead of a simple array?
But in any case, to find the specific team, you can use Underscore.
var selectedTeam = _.findWhere(teams, {code: 'EFU'});

HTML 5 App local database

I am creating a Q & A app for Windows 8 Phone.
These Q & A are about 100 or so and will never change.
I am not familiar with Windows 8 Phone SDK so I have decided to stick with the HTML 5 template for this.
Now I need to save/store these QA somewhere I do not want to involve the use of database, as this is a pretty simple app that I am making and I dont want it to connect to / depend on server, I want users to be able to use and read all QA even when they are offline.
So, with these requirement I could only think of storing these QA in json format and then using jquery to read and populate the QA into HTML.
{
"categoryName": "Animal",
"categoryId": 1,
"QA": [
{
"question": "Which animal barks ?",
"answer": "dog"
},
{
"question": "Which animal moos ?",
"answer": "cow"
},
]
}
{
"categoryName": "Grammar",
"categoryId": 2,
"QA": [
{
"question": "Opposite of men ?",
"answer": "women"
},
{
"question": "Vowels ?",
"answer": "AEIOU"
},
]
}
Are there any other approaches which you can suggest ?
Please share your thoughts on this.
According to caniuse you should be able to use HTML5 IndexedDB with IE10
You say the data will never change, so I don't see why you need to use HTML5 IndexedDB.
You don't even need to store it in JSON format, just create the JS objects directly for optimal performance:
var data = [{
categoryName: "Animal",
categoryId: 1,
QA: [
{
question: "Which animal barks ?",
answer: "dog"
},
{
question: "Which animal moos ?",
answer: "cow"
},
]
},
{
categoryName: "Grammar",
categoryId: 2,
QA: [
{
question: "Opposite of men ?",
answer: "women"
},
{
question: "Vowels ?",
answer: "AEIOU"
},
]
}];

Resources