Get about -> title and about -> images -> name from my local .json file - arrays

I want to show all images in my app.component.html file using *ngFor loop.
This is my app.component.html
<app-nav></app-nav>
<div class="container mt-4">
<router-outlet></router-outlet>
</div>
<ul>
<li *ngFor="let users of Users">
<h2>{{users.name}}</h2>
</li>
</ul>
This is my data.json
{
"about": {
"title":"STORY ABOUT US",
"subtitle":"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore et",
"images":[
{
"name":"aa1.jpg",
"id":1,
"link":"http://google.com/",
"icon":"fa fa-link"
},
{
"name":"aa2.jpg",
"id":2,
"link":"http://google.com/",
"icon":"fa fa-link"
}
]
}
This is my app.component.ts
import { Component } from '#angular/core';
import sampleData from '../assets/data.json';
#Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] })
export class AppComponent { Users: any = sampleData; }

Given your JSON data the component template should look like the following:
<h1>{{users.about.title}}</h1>
<ul>
<li *ngFor="let image of users.about.images">
{{image.name}}
</li>
</ul>
You want to loop over the iterable in your JSON data which is the images property and that is what *ngFor allows.
See a working stackblitz demo I made with the above description.
Note I used the property name users lowercase, instead of Users uppercase, as it is a more common convention, but still an opinion.

you can access your object property using two ways
1
object.propertyName
2
object['propertyName']
so import your json file into your object and access its properties like that
<li *ngFor="let users of Users">
<h2>{{users.name}}</h2>
<h2>{{users.title}}</h2>
<h2>{{users.image.name}}</h2>
<h2>{{users.image.id}}</h2>
</li>

Related

Best way to create expandable menu?

What's the best way to create menu like in attached photos ?
I tried to make it with:
const [firstParentActive, setFirstParentActive] = useState(false) // idea is to make useStates for all category parents and category children
const activeHandler = () => {...} // all handlers for setting 'true' in such category parents
<div
className={classes[`FullServices__parent-${active}`]}
onClick={() => activeHandler()}
>
Кузов
</div>
This way seemed to me very uncomfy and not universal. Furthermore I will refactor it all using redux-toolkit
initial state
expanded
There are many ways to use accordion menus
Add following code in src/App.js
import React from 'react';
const App = () => {
const accordionData = {
title: 'Section 1',
content: `Lorem ipsum dolor, sit amet consectetur adipisicing elit. Quis sapiente
laborum cupiditate possimus labore, hic temporibus velit dicta earum
suscipit commodi eum enim atque at? Et perspiciatis dolore iure
voluptatem.`
};
const { title, content } = accordionData;
return (
<React.Fragment>
<h1>React Accordion Demo</h1>
<div className="accordion">
<div className="accordion-item">
<div className="accordion-title">
<div>{title}</div>
<div>+</div>
</div>
<div className="accordion-content">{content}</div>
</div>
</div>
</React.Fragment>
);
};
export default App;

React JS - JSX returns [object Object] instead of string

Why this JSX hook returns [object Object] [object Object] instead of HTML string?
export default function Article (props) {
const {
content,
} = props;
console.log({content});
return (
<>
<div>
{content.replace(/<p>(.*?)<\/p>/g, (match) => {
return (
<p className="text-black">{match}</p>
);
})}
</div>
</>
)
}
Console.log print:
{
content: '<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas dignissim ac ante nec hendrerit.</p>\n' +
'\n' +
'<p>Morbi rhoncus diam quis sodales iaculis. Morbi ullamcorper consectetur ultricies. Nam vel efficitur erat.</p>'
}
Issue
Why this JSX hook returns [object Object] [object Object] instead of
HTML string?
You are attempting to render the returned of content.replace but the function you use to replace is returning a JSX object instead of a new string. You are also copying the entire match instead of just the captured group.
Solution
It is very unclear to me what you are trying to do, or why, but if you want to modify the raw HTML you can do a string replace, but you need to then use standard HTML (not JSX!!) and set the innerHTML of the div. Here you need to specify class instead of className.
<div
dangerouslySetInnerHTML={{
__html: content.replace(/<p>(.*?)<\/p>/g, (match, p1) => {
return `<p class="text-black">${p1}</p>`;
})
}}
></div>
or a bit more simple without the updater function
<div
dangerouslySetInnerHTML={{
__html: content.replace(/<p>(.*?)<\/p>/g, '<p class="text-black">$1</p>')
}}
></div>
Demo

How to delete item from array angularjs?

Why I can't remove item from array posts?
html tag for delete item
html tag
<span ng-click="remove($index)"> delete</span>
//AngularJS method where I try to delete item
blog.remove = function(index) {
blog.posts.splice(index, 1);
};
//Angular array posts
blog.posts = [{
"title": "Blog Post One",
"comments": [
{
"body":"Lorem ipsum dolor sit amet, consectetur adipisicing elit. ",
"author": "trollguy87"
}
]}];
Where can be problem?
Try passing the item to the function and getting the index from the item.
As mentioned in the below thread.
How do I delete an item or object from an array using ng-click?
If you are using ng-repeat then this can help:
<div ng-repeat="key in posts"> <!-- This will use your blog.posts -->
<button ng-click="posts.splice($index, 1)">
{{key.title}}
</button>
</div>

AngularJS: How to assign active class to clicked item in ng-repeat?

I am confused about how to show an .active class on a clicked item when using the ng-repeat directive. Here's a Plunker.
Here's my view:
<h4>Arctic Videos</h4>
<ul class="list-unstyled">
<li class="clearfix" ng-repeat="item in videos" ng-class="{ active: $index }" style="padding-bottom: 2em;">
<div style="float: left; position:relative;">
<img class="img-thumbnail" ng-src="{{item.thumbUrl}}" width="100" height="68" alt="">
</div>
<h4>{{item.title}}</h4>
</li>
</ul>
My script.js
var ArcticApp = angular.module('ArcticApp', ['ngRoute', 'ngSanitize']);
ArcticApp.config(function($routeProvider){
$routeProvider
.when('/', {
templateUrl: './partials/map.html',
controller: 'MainController'
})
.when('/videos/:itemId', {
templateUrl: './partials/videos.html',
controller: 'VideoController'
})
.otherwise({
redirectTo: '/'
})
});
ArcticApp.controller('MainController', function($scope){
$scope.message = "This is the map page!";
});
ArcticApp.controller('VideoController', function($scope, $routeParams, $sce){
$scope.videos = [
{
"blockquote": "et sint quae\nqui odio fugit quia aut modi id maxime\nsequi qui et",
"title": "Canada",
"synopsis": "<p>Some text will go here and there. Some more will go here.</p><p>Yet even some more text will go here and there. yes, tehre's even more here.</p>",
"id": 897,
"thumbUrl": "http://placehold.it/100x68"
},
{
"blockquote": "sit molestiae possimus ut in explicabo\nea autem saepe a iusto est exercitationem at\ndistinctio quia consectetur nulla vel maxime",
"title": "USA",
"synopsis": "<p>Some text will go here and there. Some more will go here.</p><p>Yet even some more text will go here and there. yes, tehre's even more here.</p>",
"id": 471,
"thumbUrl": "http://placehold.it/100x68"
},
{
"blockquote": "recusandae natus minus est saepe alias\nvero amet quia natus voluptatem ut saepe dolor rem\nperspiciatis quia unde quia cum aliquam sint",
"title": "Russia",
"synopsis": "<p>some text can go here </p>",
"id": 400,
"thumbUrl": "http://placehold.it/100x68"
}
];
$scope.whichItem = $routeParams.itemId;
$scope.trustAsHtml = $sce.trustAsHtml.bind($sce);
});
How would I go about assigning an active class to a clicked item?
Use
ng-class="{ active: selectedVideo === item }"
And
ng-click="selectVideo(item)"
In the controller, add
$scope.selectVideo = function(video) {
$scope.selectedVideo = video;
}
you can use it like this
<li class="clearfix" ng-repeat="(key,item) in videos" ng-class="{ active:(condition) }" style="padding-bottom: 2em;">
key is the number of iteration and condition can be any Boolean logic to make active class true
like
ng-class="{ active: 1==1 }
in this case since 1==1 is true so active class will be printed .

Filter date range using jQuery UI calendars in AngularJS data-bound table

I have a series of HTML tables which pull data from JSON sources. These are tabbed. They work fine and can be seen in the fiddle here:
Fiddle: http://jsfiddle.net/nA28B/1/.
What I need to do now though is use the date range inputs (which are integrated as jQuery UI datepickers) to filter the data in the tables by the date column. I'm new to AngularJS and the integration with the jQuery UI datepickers particularly has taken this way over my head and I'm struggling to find the solution.
I've tried adding an ng-change attribute to the date inputs but can't even get this to fire a simple alert - possibly I've not set up controllers in the correct places (I've tried creating a new controller around the filter inputs to no avail)?
The code for this is pretty lengthy but quite straight forward, as follows:
HTML:
<div ng-app="myApp">
<h2>Tabs:</h2>
<div class="tabs" ng-init="selected=1">
Purchases
Products on sale
Last 30 days sales
</div>
<h2>Filters:</h2>
<div>
<label for="fromDate">From date:</label> <input type="text" name="fromDate" value="from date..." ng-model="dateFrom" datepicker />
</div>
<div>
<label for="toDate">To date:</label> <input type="text" name="toDate" value="to date..." ng-model="dateTo" datepicker />
</div>
<div class="selected" ng-controller="PurchasesCtrl" ng:show="selected == 1">
<h3>Purchases:</h3>
<table cellspacing="0">
<tr class="first">
<th class="first">Date</th>
<th>Description</th>
</tr>
<tr ng-repeat="purchase in purchases.data" ng-class-odd="'odd'" ng-class-even="'even'" ng-class="{'last':$last}">
<td class="first">{{purchase.date}}</td>
<td>{{purchase.text}}</td>
</tr>
</table>
</div>
<div class="selected" ng-controller="SaleProductsCtrl" ng:show="selected == 2">
<h3>Sale products:</h3>
<table cellspacing="0">
<tr class="first">
<th class="first">Date</th>
<th>Description</th>
</tr>
<tr ng-repeat="saleProduct in saleProducts.data" ng-class-odd="'odd'" ng-class-even="'even'" ng-class="{'last':$last}">
<td class="first">{{saleProduct.date}}</td>
<td>{{saleProduct.text}}</td>
</tr>
</table>
</div>
<div class="selected" ng-controller="Sale30DaysCtrl" ng:show="selected == 3">
<h3>Sale 30 days:</h3>
<table cellspacing="0">
<tr class="first">
<th class="first">Date</th>
<th>Description</th>
</tr>
<tr ng-repeat="sale30Day in sale30Days.data" ng-class-odd="'odd'" ng-class-even="'even'" ng-class="{'last':$last}">
<td class="first">{{sale30Day.date}}</td>
<td>{{sale30Day.text}}</td>
</tr>
</table>
</div>
</div>
JS:
var myApp = angular.module("myApp",[]);
myApp.factory("Purchases", function(){
var Purchases = {};
Purchases.data = [
{
date: "10/05/2012",
text: "Lorem ipsum dolor sit amet ipsum dolor"
},
{
date: "05/05/2012",
text: "Lorem ipsum dolor sit amet ipsum dolor"
},
{
date: "20/05/2012",
text: "Lorem ipsum dolor sit amet ipsum dolor"
}
];
return Purchases;
});
function PurchasesCtrl($scope, Purchases){
$scope.purchases = Purchases;
}
myApp.factory("SaleProducts", function(){
var SaleProducts = {};
SaleProducts.data = [
{
date: "10/05/2012",
text: "Lorem ipsum dolor sit amet ipsum dolor"
},
{
date: "28/05/2012",
text: "Lorem ipsum dolor sit amet ipsum dolor"
}
];
return SaleProducts;
});
function SaleProductsCtrl($scope, SaleProducts){
$scope.saleProducts = SaleProducts;
}
myApp.factory("Sale30Days", function(){
var Sale30Days = {};
Sale30Days.data = [
{
date: "06/05/2012",
text: "Lorem ipsum dolor sit amet ipsum dolor"
},
{
date: "08/05/2012",
text: "Lorem ipsum dolor sit amet ipsum dolor"
},
{
date: "21/05/2012",
text: "Lorem ipsum dolor sit amet ipsum dolor"
},
{
date: "20/05/2012",
text: "Lorem ipsum dolor sit amet ipsum dolor"
}
];
return Sale30Days;
});
function Sale30DaysCtrl($scope, Sale30Days){
$scope.sale30Days = Sale30Days;
}
myApp.directive('datepicker', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
$(function () {
element.datepicker({
dateFormat: 'dd/mm/yy',
onSelect: function (date) {
ngModelCtrl.$setViewValue(date);
scope.$apply();
}
});
});
}
}
});
Can anyone set me on the right track with this please? I've tried everything I can think of but I've reached my AngularJS limit!
EDIT:
I've simplified the example just to try to get the basic date filtering working, so I can then get the tabs etc hooked up afterwards. Here's a simplified fiddle:
SIMPLIFIED FIDDLE: http://jsfiddle.net/bY3YL/1/
Well, your problem was quite simple, your input was outside of you controller, so even though you would had used ng-change, it would had never been called.
I fixed your code here. I also added the filtering function; it's only for the From Date input field, but I think you might figure the To Date one by yourself.
$scope.onChangeFromDate = function() {
var fromDate = $.datepicker.parseDate('dd/mm/yy', $scope.dateFrom);
angular.forEach($scope.purchases.data, function(purchase){
var purchaseDate = $.datepicker.parseDate('dd/mm/yy', purchase.date);
if(purchaseDate.getTime() < fromDate.getTime()) {
purchase.filtered = true;
}
})
}

Resources