Angular: data is not showing up in UI - html

I am trying to access values in a list object, but data not showing up in UI, not sure why?
i can see the data in the console log. Below are the angular model interface i am using and
angular class,HTML code and Mock data, what am i doing wrong ?
Interfaces
export interface MycodeType {
SpecialCode?: Mycodes[];
}
export interface Mycodes {
SpeicalCode: number;
SpecialCodeDescription: string;
SpecialProvidedStatus: string;
}
My Angular Component file:
export class SpecialCodesComponent implements OnInit {
#Input('sFC') specialFeatureCodes: MycodeType;
constructor() {}
specialCodesColumns: any[];
ngOnInit(): void {
this.specialFeatureCodesColumns = [
{ field: 'specialCode', header: 'Special Code', width:'125%' },
{ field: 'specialDescription', header: 'Special Code Description', width:'75%' },
{ field: 'providedDerived', header: 'Provided/Derived', width:'125%' },
];
}
}
HTML:
<div *ngIf="specialCodes?.SpecialCode.length>0" class="row"
style="padding-left: 0px;padding-right: 25px; text-align:center">
<fm-table [columns]="specialCodesColumns" [value]="specialCodes.SpecialCode">
<ng-template fmTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns" style="text-align: center; font-size: 15px;">{{col.header}}</th>
</tr>
</ng-template>
<ng-template fmTemplate="body" let-rowData let-columns="columns">
In the console log i see the data
SpecialCode: Array [ {…}, {…} ]
*But data is not showing up in UI
Mock data is that i am using to populate on UI screen:
"SpecialCodes":{
"SpecialCode":[
{
"SpecialCode": "118",
"SpecialCodeDescription": "some Second data",
"SpecialCodeProvidedStatus": "Provided"
},
{
"SpecialCode": "127",
"SpecialCodeDescription": "some data test",
"SpecialCodeProvidedStatus": "Derived"
}

Related

How to display mock data in html in Angular

I have created mock service file and I want to display in my html but not really sure how to make it display properly so I'll be really appreciated If I can get any help or suggestion.
<div class="container2">
<div class="header" style="height: 400px">
<div class="content3">
<div>
<h1 class="kpi-title">90,346</h1>. // I'm trying to remove this hard code html
<p class="kpi-des">Users Right Now</p> // and display it from my mock data file.
</div>
<div>
<h1 class="kpi-title">250++l</h1>
<p class="kpi-des">Saved</p>
</div>
<div>
<h1 class="kpi-title">$34.5 mill</h1>
<p class="kpi-des">New User per Week</p>
</div>
</div>
</div>
</div>
TS
import { ProductService } from '../../data/product-suite.service';
export class MaxisProductSuiteComponent {
productService: ProductService[];
ngOnIT(){
}
product-suite.service.ts
export class ProductService {
productsuite: ProductSuite[] = [
{
id: 1,
title: '90,346',
description: 'Users',
},
{
id: 2,
title: '$34.5 mill',
description: 'Saved',
},
{
id: 3,
title: '250++',
description: 'New User per Week',
},
];
}
Please find the below code for your solutions:
create a json file assets folder with name output.json.
{
"result" : [
{
"id": 1,
"title": "90,346",
"description": "Users at Ford"
},
{
"id": 2,
"title": "$34.5 mill",
"description": "Saved for Ford"
},
{
"id": 3,
"title": "250++",
"description": "New User per Week"
},
{
"id": 4,
"title": "64%",
"description": "Users At Ford"
}
]
}
in service file write below code:
import { observable, Observable } from "rxjs";
import { MaxisProductSuite } from "src/Model/model";
import { HttpClient } from '#angular/common/http';
import { Injectable } from "#angular/core";
#Injectable()
export class MaxisProductService {
constructor(private http: HttpClient){}
getAllMaxisps():Observable<MaxisProductSuite> {
return this.http.get<MaxisProductSuite>("./assets/output.json");
}
}
then component file add below code:
import { DOCUMENT } from '#angular/common';
import { Component, Inject, OnInit } from '#angular/core';
import { MaxisProductSuite } from 'src/Model/model';
import { MaxisProductService } from 'src/service/MaxisProductService';
#Component({
selector: 'app-temp',
templateUrl: './temp.component.html',
styleUrls: ['./temp.component.scss']
})
export class TempComponent implements OnInit {
maxisps: MaxisProductSuite[];
public resultData:MaxisProductSuite=null;
constructor(#Inject(DOCUMENT) private document: Document, private service : MaxisProductService) {}
ngOnInit() {
this.service.getAllMaxisps().subscribe((res:MaxisProductSuite) => {
console.log(res);
this.resultData =res;
});
}
}
then HTMl file add below code:
<div *ngFor="let item of resultData?.result">
<div class="header" style="height: 400px">
<h1>{{item.id}}</h1>
<h2>{{item.title}}</h2>
<h3>{{item.description}}</h3>
</div>
add below model in model file
export interface MaxisProductSuite {
result : Result[]
}
export interface Result{
id?: number;
title: string;
description: string;
}
I hope it will help you to get the solution.
happy to HELP!
make your service in module provider or make it injectable "root".
inject the service in your component you want to display data in constructor as a dependency injection.
assign your component variable array with productService.
in your HTML loop about your data array using *ngFor=" let product of products".
use you product value in the interpolation {{ product.id }}.

How to pull object from component to html angular?

How can I pull an object from component to html angular?
Here is my component file code:
export class DetailsComponent implements OnInit {
authorID: string;
authorData: any = {};
constructor(
private router: Router,
private route: ActivatedRoute,
private httpService: HttpService
) {}
ngOnInit() {
this.authorID = this.route.snapshot.paramMap.get("id");
console.log(this.authorID);
this.getSingleAuthor();
}
getSingleAuthor() {
let observable = this.httpService.getOneTask(this.authorID);
observable.subscribe((data) => {
this.authorData = data;
console.log(this.authorData);
});
}
}
and here is my html code:
<button class="btn btn-info btn-sm" [routerLink]="['/write', 1]">Add Quote</button>
<div class="info" *ngFor="let info of authorData">
<p>Quote by {{info.name}}: </p>
<table class="table border">
<thead class="thead-light">
<tr>
<th>Quote</th>
<th>Votes</th>
<th>Action available</th>
</tr>
</thead>
</div>
I tried to pull out author name from an object in component but it didnt work out.
I tried to for loop and it worked but in my console it showed this error:
This is my author model:
const AuthorSchema = new mongoose.Schema({
name: {
type: String,
required: [true, "Name is Required"],
minlength: [3, "Must be longer than 3 characters"]
},
author_quote: [{
quote: {
type: String,
minlength: [3, "Must be longer than 3 characters"]
},
vote: Number
}]
})
Cannot find a differ supporting object '[object Object]' of type 'object'
Ehy !
i assume that authorData is just an object of the kind:
{
name
age
...
}
So it's quite difficult that you need to iterate it with an *ngFor that is instead used for collections.
You should just ensure to render the portion of html that uses those data when they are ready:
Leave the authorData to undefined in your component: authorData: any;
Use an *ngIf in your template, so you will render that html when the author's data are available:
<div *ngIf="authorData" class="info">
<p>Quote by {{ authorData.name }}: </p>
...
</div>
As alternative you can avoid to subscribe to the observable in the component and use an async pipe approach

How can I display last property in a JSON object first in the UI

I have a JSON of following format:
[
{Details: [{name: "WII", type:"Video Games", id:"lint"}]
]
however on the UI in a table, I want to display ID first in the first column followed by the others.
Let's assume this is your JS data structure:
let list = [
{ Details: [{ name: "WII", type: "Video Games", id: "lint" }] }
];
Then in your Angular component template:
<table>
<tr *ngFor="let item of list" >
<td>{{item.Details[0].id}}</td>
<td>{{item.Details[0].name}}</td>
<td>{{item.Details[0].type}}</td>
</tr>
</table>
Of course, this is not ideal but to give you a better answer/solution you should provide more information.
You can make use of Pipe to get the keys and reverse it.
import { PipeTransform, Pipe } from '#angular/core';
#Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
transform(value, args:string[]) : any {
let keys = [];
for (let key in value) {
keys.push(key);
}
return keys.reverse();
}
}
STACKBLITZ DEMO

Angular dynamic table using ngFor

I would like to know if it is possible to create a dynamic HTML table from JSON data. The amount of columns and headers should change according to the keys in the JSON. For example this JSON should create this table:
{
color: "green", code: "#JSH810"
}
,
{
color: "red", code: "#HF59LD"
}
...
And this JSON should create this table:
{
id: "1", type: "bus", make: "VW", color: "white"
}
,
{
id: "2", type: "taxi", make: "BMW", color: "blue"
}
...
This has to be 100% dynamic though, because I want to display hundreds of different JSON objects, so nothing should be hard coded in the HTML page.
If you want to get the key of your object as the head of your table, you should create a custom pipe.
import { PipeTransform, Pipe } from '#angular/core';
#Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
transform(value, args:string[]) : any {
let keys = [];
for (let key in value) {
keys.push(key);
}
return keys;
}
}
Update: Or simply return keys using Object.keys().
(demo)
#Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
transform(value, args:string[]) : any {
return Object.keys(value);
}
}
Now into your html template:
<table>
<thead>
<tr>
<th *ngFor="let head of items[0] | keys">{{head}}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of items">
<td *ngFor="let list of item | keys">{{item[list]}}</td>
</tr>
</tbody>
</table>
Update: Here is the demo.
This can help:
export class AppComponent {
//Array of any value
jsonData:any = [
{id: "1", type: "bus", make: "VW", color: "white"},
{id: "2", type: "taxi", make: "BMW", color: "blue"}
];
_object = Object;
}
<div>
<table border="1">
<thead>
<tr>
<th *ngFor="let header of _object.keys(jsonData[0]); let i = index">{{header}}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let row of jsonData; let i = index">
<th *ngFor="let objKey of _object.keys(row); let j = index">{{ row[objKey] }} </th>
</tr>
</tbody>
</table>
</div>

Angular2 Getting very deep nested json value using pipe! *ngFor

Hi I am having trouble getting json value which is really deeply nested using pipe.
What am I doing wrong?
Pipe I'm using
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({
name: 'keyValues'
})
export class KeysPipe implements PipeTransform {
transform(value, args: string[]): any {
let keys = [];
for (let key in value) {
keys.push({
key: key,
value: value[key]
});
}
return keys;
}
}
Json I'm getting from server.
data:
0: {
Profile: { ...
}
BasicInfo: { ...
}
introduceInfo: {
curriculum: { ...
}
experience: {
0: {
category: "Mentor"
year: "2011"
duration: "24"
}
1: {
category: "Student"
year: "2011"
duration: "14"
}
}
}
}
It's actually a huge json object but I've simplified to only show what I need to get.
I want to get the value of category (which is "Mentor"and "Student".
And to do so, I've tried in my html
<div *ngFor="let detail of teaInfo | keyValues">
<div *ngFor="let experience of detail.value['introduceInfo'] | keyValues">
<div *ngFor="let exp of experience.value['experience'] | keyValues">
<p class="fontstyle2">{{exp.value['category']}} {{exp.value['year']}}년 | {{ex.value['duration']}}개월</p>
</div>
</div>
</div>
And I'm getting my json object in my component like this.
teaInfo: any[];
getTeacherDetail(): void {
let params = new URLSearchParams();
params.set('gradeType', `${this.getVal2()}`)
params.set('subjectType', `${this.getVal3()}`)
params.set('district', `${this.getVal1()}`)
this.teaDetail.getTeachersDetail(params)
.subscribe(
teaInfo => this.teaInfo = teaInfo,
error => this.errorMessage = error
)
}
And the result is I am getting nothing
What am I doing wrong?
Trying to interpret how your JSON looks like, something like this:
{
"data":{
"0": {
"Profile":{
"prof":"prof"
},
"BasicInfo":{
"basic":"basic"
},
"introduceInfo":{
"curriculum": {
"curr":"curr"
},
"experience":{
"0":{
"category":"Mentor",
"year":"2011",
"duration":"24"
},
"1":{
"category":"Student",
"year":"2011",
"duration":"14"
}
}
}
}
}
}
In below example, I have extracted the values from data, so:
.map(res => res.json().data)
To reach values Mentor and Student, first change your pipe to this:
export class KeysPipe implements PipeTransform {
transform(value: any, args: any[] = null): any {
return Object.keys(value).map(key => value[key]);
}
}
and change your HTML to this:
<div *ngFor="let detail of teaInfo | keyValues">
<div *ngFor="let experience of detail['introduceInfo']['experience'] | keyValues">
{{experience.category}}
</div>
</div>
This should work nicely:
Demo