Displaying comma separated string in Angular 6 - html

I am trying to loop through a comma separated string in Angular 6.
public getCategory(){
this.Jarwis.getCategorys().subscribe((data: Array<object>) => {
this.categorys = data;
console.log(this.categorys);
});
This is my function which have a console log as
(3) [{…}, {…}, {…}, {…}, {…}, {…}]
0: {id: 4, category_name: "Agriculture", sub_category_names: "Other Agriculture,Vineyards and Wineries,Greenhouses,Tree Farms and Orchards"}
1: {id: 5, category_name: "Automotive and Boat", sub_category_names: "Auto Repair and Service Shops,Car Dealerships,Marine/Boat Service and Dealers,Junk and Salvage Yards"}
2: {id: 13, category_name: "Beauty and Personal care", sub_category_names: "Massage,Tanning Salons,Spas,Hair Salons and Barber Shops"}
I can display category name in view page with the help of
<li *ngFor='let category of categorys'>
<div>{{ category.category_name }}</div>
</li>
But how can I display sub_category_names in different divs just like this
<div> subcategory_name1 </div>
<div> subcategory_name2 </div>
Please help

You can use a custom pipe to split the array:
#Pipe({
name: 'splitComma'
})
export class SplitCommaStringPipe implements PipeTransform {
transform(val:string):string[] {
return val.split(',');
}
}
and use it like:
<div *ngFor="let subcategory of category.sub_category_names|splitComma">
{{subcategory}}
</div>

Use following code in your html:
<li *ngFor='let category of categorys'>
<div>{{ category.category_name }}</div>
<div *ngFor="let subCategory of category.sub_category_names?.split(',')">
{{ subCategory }}
</div>
</li>

May be you can try this way by using an additional *ngFor
<li *ngFor='let category of categorys'>
<div *ngFor="let subCategory of (category.sub_category_names.split(','))">{{ subCategory }}</div>
</li>
https://stackblitz.com/edit/angular-a4s1bq

You can also split the sub-categories on return of the data. And then use *ngFor on the sub-categories. In ES6 this would look like this:
this.categories = data.map((e => {
return {
...e,
sub_category_names: e.sub_category_names.split(',')
}
}));
btw. plural of category is categories
https://stackblitz.com/edit/js-rkkyjs

Related

How I can parse object to array in angular?

I get an object from an array of elements, and I need to parse it as an array and display it as a list, can you tell me how to do this? I only know how to handle requests.
html:
<ul *ngFor="let filtered of reposFiltered">
<li>
{{filtered.name}}
{{filtered.description}}
{{filtered.language}}
{{filtered.html}}
</li>
</ul>
.ts:
// Required data
selectRepo(data){
this.reposFiltered = data;
console.log(data)
}
massive with objects:
0: cu {name: "30daysoflaptops.github.io", description: null, language: "CSS", html: "https://github.com/mojombo/30daysoflaptops.github.io"}
1: cu {name: "asteroids", description: "Destroy your Atom editor, Asteroids style!", language: "JavaScript", html: "https://github.com/mojombo/asteroids"}
etc
If you only wish to see the data in the rows you could use the following code:
// the data
const data = [
{name: "30daysoflaptops.github.io", description: null, language: "CSS", html: "https://github.com/mojombo/30daysoflaptops.github.io" },
{name: "asteroids", description: "Destroy your Atom editor, Asteroids style!", language: "JavaScript", html: "https://github.com/mojombo/asteroids"}
];
// Required data
selectRepo(data){
this.reposFiltered = data.map(row => Object.values(row));
}
//html
<!-- iterate through all data rows -->
<ul *ngFor="let row of reposFiltered">
<!-- iterate through all values -->
<li *ngFor="let value of row">
{{ value }}
</li>
</ul>
To iterate over the properties on an object you need to use the https://angular.io/api/common/KeyValuePipe
something like this:
<ul *ngFor="let filtered of reposFiltered | keyvalue">
<li>
{{filtered.value.name}}
{{filtered.value.description}}
{{filtered.value.language}}
{{filtered.value.html}}
</li>
</ul>
If you need to access the key:
{{filtered.key}}
This code is useful for debugging:
{{filtered.key | json}}
{{filtered.value | json}}

How to bind a single element from a model object in angular in a template

Can someone give me a clue, how to bind a variable value from a .model created?
I have used ng for in a div, then I can interpolate values from a .model.ts using:
ngFor let list of lists
then i {{name.list}}
But in other div, I just can show a dynamic name of a .model.ts, like name.list.
How can I do this?
Thanks
If you have in your component some data like:
usersList = [
{ name: "Michael", id: 1 },
{ name: "Linda", id: 2 }
];
In your template html you should do something like this:
<h2>List of users</h2>
<ul *ngIf="userList.length">
<li *ngFor="let user of userList">
Hello {{user.name}} (id: {{user.id}})
</li>
</ul>
<div *ngIf="!userList.length">No users</div>

Nuxt how to loop on an array and display the data properly with a v-for

I have an e-commerce site, I want to loop the nested data from json. I tried many things but couldn't find.
async fetch() {
this.post = await fetch(
`http://test.com/api.php?id=${this.$route.params.id}`
).then((res) => res.json())
}
I use like this;
<h3>{{ post.title }}</h3>
<li v-for="(index, post.sizes) in sizes" :key="index">
{{ sizes.index }}
</li>
My json Data is : "sizes": "[\"XS\",\"S\",\"M\",\"L\"]",
thanks for helping.
Having this kind of code is not really okay.
<li v-for="(size, index) in sizes" :key="index">
{{ size }}
</li>
You need to update your data to something like this
sizes: [
{ id: 1, name: "XS" },
{ id: 2, name: "S" },
{ id: 3, name: "M" },
{ id: 4, name: "L" },
]
Or even better, fetch some ids from an API and then, use it like this
<li v-for="size in sizes" :key="side.id">
{{ size.name }}
</li>
Having a mutable index is not something that you should use for :key since it's does the opposite of what is is supposed to do.
:key is essential, more info here: https://v2.vuejs.org/v2/style-guide/#Keyed-v-for-essential
Here a blog article explaining this: https://michaelnthiessen.com/understanding-the-key-attribute#dont-use-an-index-as-the-key

Displaying object into HTML in Angular

sorry for the noob question.
I created an http request and retrieved some pokemon data and put it in an object called pokemon, like so:
export class AppComponent implements OnInit{
title = 'Pokedex';
apiURL = 'https://pokeapi.co/api/v2/pokemon/1';
pokemon = {};
constructor(private http: HttpClient){}
ngOnInit(): void{
this.http.get(this.apiURL).subscribe(data =>{
const pokemon = {
name: data['name'],
id: data['id'],
abilities: data['abilities'].map( ability => ability['ability']['name']),
types: data['types'].map( type => type['type']['name']),
image: data['sprites']['front_default']
}
console.log(pokemon);
When I console log the object, it outputs in the console fine.
However, when I try to display it in an html {{ pokemon }} it just returns [object, Object]
How can I get around this?
I have tried the methods suggested below.
{{pokemon.name}}, {{pokemon[name]}} and {{pokemon?.name} display a blank page.
{{ pokemon | json }} returns an empty object, in the form of {}.
Am I perhaps doing something else wrong?
You need to use the json pipe
<pre>{{ pokemon | json }}</pre>
OR
<div> Id: {{ pokemon.id }} </div>
<div> Name: {{ pokemon.name }} </div>
<div> Abilities:
<ul>
<li *ngFor="let ability of pokemon.abilities"> {{ ability }}</li>
</ul>
</div>
<div> Types:
<ul>
<li *ngFor="let type of pokemon.types"> {{ types }}</li>
</ul>
</div>
call property as {{pokemon?.name}}
You can't use object directly. You have to access object properties by either . (Dot) notation or object[property] way.
In your case, if you want to use the property of name then use
{{ pokeman.name }}
or
{{ pokeman[name] }}

Access nested json object angular 6

I'm trying to access the nested data from the HTML template, but I get undefined or I get nothing as result (empty page with no class list or student list).
The HTML template:
<div class="container">
<label *ngFor="let class of listClass | keyvalue">
<span> {{class.value.name}} </span>
</label>
<div>
<label *ngFor="let student of class.students | keyvalue">
<span>{{student.value.fullName}} </span>
</label>
</div>
</div>
This is the fonction that gets the list of class and the students in it:
getListClasseStudent(){
this.classService.getStudents().subscribe((data) => {
this.listClass = data;
});
}
The nested data:
class:
0:{
code: "Math01"
teacher:
0: {id: 17551, name "Jack"}
students:
0: {studentId: 1, fullName: "Patrick bob"}
1: {studentId: 2, fullName: "Alice Alice"}
}
1:{
code: "English01"
teacher:
0: {id: 2, name "Nicolas"}
students:
0: {studentId: 1, fullName: "Patrick bob"}
1: {studentId: 2, fullName: "Alice Alice"}
}
I want to access to the list of student of each class, is there any efficient way to do it? thanks in advance.
<div class="container">
<div *ngFor="let c of listClass ">
<label >
<span> {{c.code}} </span>
</label>
<div>
<label *ngFor="let student of c.students ">
<span>{{student.fullName}} </span>
</label>
</div>
</div>
Try this (example without your pipe)
A 'Class' object don't have a attribute 'value.name' (probably gonna be injected by your pipe '| keyvalue' ).
Second *ngFor need t be inside of first, because he need's to iterate a students array, inside each class.
I hope this helps.
create a pipe like below
import { Pipe, PipeTransform } from "#angular/core";
#Pipe({ name: 'ObjNgFor', pure: false })
export class ObjNgFor implements PipeTransform {
transform(value: Object): Array<string> { return Object.keys(value); }
}
import the above pipe in app.module.ts and use pipe in the html page like below
<div *ngFor="let key of questions | ObjNgFor" class="row">
{{ questions[key].name}}
<div *ngFor="let r of questions[key].sub_sections | ObjNgFor ; let indx=index"
class="card-body">
{{ questions[key].sub_sections[r].name }}"
</div>
This example should work