I am fetching data from an api server and storing it as a object in TypeScript, I need help referencing that data in HTML as a key and value pair.
TypeScript:
if (x.AttributeTemplateId==templateId) {
x['AttributeTemplateValue'].forEach(function(x){
console.log('hello');
if (x.AttributeTemplateId==templateId){
console.log(templateId);
(function(y){
console.log("hello2");
newName.push(y.CodeSet);
newValue.push(y.CodeValue);
// console.log([newAttributes]);
})(x);
}
})
}
})
newName = this.name;
newValue = this.value;
this.attributes = this.name.reduce((acc, value, i) => (acc[value] = this.value[i], acc), {});
console.log(this.attributes);
}
My data is in this.attributes and it looks like this
I want to put key and value in a table like
<table>
<tr>
<th> Name </th>
<th> Value </th>
</tr>
<tr key>
<td value > </td>
</tr>-->
</table>
How would I achieve this in Angular2 ?
step 1: Create a custom pipe that stores all the object keys and values in an array and returns them just like this
import { PipeTransform, Pipe} from '#angular/core';
#Pipe({name: objKeys})
export calss objKeysPipe implements PipeTransform {
transform(value, arguments: string[]) :any {
let keys= [];
for (let k in value){
keys.push({key: k, value: value[k]});
}
return keys;
}
setp 2: in your component template you do the folowing
<table>
<tr *ngFor="let att of attributes | objKeys">
<th>{{att.key}}</th>
<th>{{att.value}}</th>
</tr>
</table>
Related
i have a list of data and i show it in the tabel :
<table style="width: 100%;border:2px solid black;">
<tr>
<th>Avatar</th>
<th>Firstname</th>
<th>Get Detail in Model</th>
<th>Action</th>
</tr>
<tr>
<td> <input [(ngModel)]="idSearch" placeholder="Id" /></td>
<td> <input [(ngModel)]="nameSearch" placeholder="Name" /></td>
</tr>
<tr *ngFor="let item of usersList ">
<td><img [src]="item.picture" /></td>
<td>{{ item.name }}</td>
<td><a (click)="GetDetail(item._id)">Detail</a></td>
<td><a (click)="Delete(item)">Delete</a></td>
</tr>
</table>
and this is my service for get items :
GetUsers(): Observable<any> {
return this.httpClient.get<any>('../resources/users.json').pipe(
map(res => {
if (res) {
return res;
}
return null;
})
)
}
now i want to create a component for search in the list , when user fill the input and click on the search button the list must be refreshed .
this is Demo of my Issue
how can i solve this problem ????
You can pass the fetched JSON to filter component as Input and also have the service injected there, incase the input is not received, you can call the service there itself.
After filtering the data, pass the filtered data to App Component.
Filter Comp.html
<button (click)="search()">Search</button>
Filter comp.ts
export class SearchByFilterComponent implements OnInit {
#Input() userList: any[];
#Output() filteredList = new EventEmitter();
searchName:string = '';
constructor(private userService: UserManagerService) { }
ngOnInit() {
}
search() {
if (this.userList) {
this.filter();
} else {
this.userService.GetUsers().subscribe(data => {
this.userList = data;
this.filter();
})
}
}
filter() {
if (this.userList) {
const filteredData = this.userList.filter(ob => {
return ob.name.toLowerCase().includes(this.searchName.toLowerCase());
});
this.filteredList.emit(filteredData)
}
}
}
App.html
<app-search-by-filter (filteredList)="updateList($event)" [userList]="usersListToSend"></app-search-by-filter>
App.comp.ts
usersListToSend: any[];
FetchData(): void {
this.userService.GetUsers().subscribe(data => {
console.log(data);
this.usersList = data;
this.usersListToSend = data;
})
}
updateList(e) {
this.usersList = e;
}
Above are the suggested new changes, the rest of your code remains same.
This filtering should ideally be done at the API level but since we have the JSON here we are querying the it everytime.
I need to create one matrix table of each combination by comparing the two array object using Angular. I am explaining my code below.
ColumnNames= ["Colour", "Size"];
configArr={
"Colour":["Black", "Red", "Blue","Grey"],
"size": ["XS","S","XL","XXL","M"]
}
Here I have two array. My first array ColumnNames values will be the table column header and accordingly I need to create the matrix like below.
Expected output::
Colour Size
Black XS
Black S
Black XL
Black XXL
Black M
Red XS
Red S
Red XL
Red XXL
Red M
.................
................
................
Like the above format I need to display the data into angular table. I need only create the matrix dynamically.
A generic solution that works with any configArr, as long as all keys in that object are string[]. Inspired by this.
app.component.ts
import { Component, OnInit } from "#angular/core";
#Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
name = "Angular";
// Comment in/out properties here to see how the table changes
configArr = {
Colour: ["Black", "Red", "Blue", "Grey"],
Size: ["XS", "S", "XL", "XXL", "M"],
//Price: ["$5", "$10", "$15"],
//Brand: ["B1", "B2", "B3"]
};
// This will be an [] of objects with the same properties as configArr
matrix;
allPossibleCases(arr) {
// Taken almost exactly from the linked code review stack exchange link
}
ngOnInit() {
const configKeys = Object.keys(this.configArr);
const arrOfarrs = configKeys.map(k => this.configArr[k]);
const result = this.allPossibleCases(arrOfarrs);
this.matrix = result.map(r => {
const props = r.split(' ');
let obj = {};
for(let i=0;i<props.length;i++) {
obj[configKeys[i]] = props[i]
}
return obj;
});
}
}
app.component.html
<table>
<thead>
<tr>
<th *ngFor="let kv of configArr | keyvalue">{{ kv.key }}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let elem of matrix">
<td *ngFor="let kv of elem | keyvalue">{{ kv.value }}</td>
</tr>
</tbody>
</table>
Stackblitz.
Also, see this for the algorithm behind it.
Try like this:
<table>
<tr>
<th *ngFor="let heading of ColumnNames"> {{heading}} </th>
</tr>
<ng-container *ngFor="let color of configArr.Colour">
<tr *ngFor="let size of configArr.size">
<td>{{color}}</td>
<td>{{size}}</td>
</tr>
</ng-container>
</table>
Working Demo
configArr.Colour.forEach((color) => {
configArr.size.forEach((size) =>{
console.log(color ," ", size); // Change this according to your table
})
})
I have three variables and i was created one array and pushed all these three variables in to this array.
And in my html template i am using a table. I tried with *ngFor but it is not working and also i tried with string interpolation and that too not woriking.
I am getting an error called <--can not read property "title" of undefined-->
In my console i am getting data like this....
array of data
(3)[{...}{...}{...}]
0:{key:"-LtZprPfMtDgzuxmaI5o"}
1:{price:1}
2:{title:"title1"}
array of data
(3)[{...}{...}{...}]
0:{key:"-LtcY8_6dd8fzibK9EYV"}
1:{price:2}
2:{title:"title2"}
array of data
(3)[{...}{...}{...}]
0:{key:"-LtcZF9NHknDZ0OcKzHg"}
1:{price:3}
2:{title:"title3"}
And here my product.component.ts
import { ProductsService } from './../../products.service';
import { Component, OnInit } from '#angular/core';
import { AngularFireDatabase, AngularFireAction, DatabaseSnapshot } from 'angularfire2/database';
#Component({
selector: 'app-admin-products',
templateUrl: './admin-products.component.html',
styleUrls: ['./admin-products.component.css']
})
export class AdminProductsComponent{
constructor(
private products:ProductsService,
private db : AngularFireDatabase
) {
products.getAll().on('child_added',function(c){
let data = c.val();
let key = c.key;
let price = data.price;
let title = data.title;
let array=[];
array.push({"key":key});
array.push({"title":title});
array.push({"price":price});
console.log('array of data',array);
})
}
}
And my admin-products.component.html
<table class="table">
<thead>
<th>Title</th>
<th>Price</th>
<th></th>
</thead>
<tbody *ngFor="let p of array">
<td>{{p.title}}</td>
<td>{{p.price}}</td>
<td ><a [routerLink]="['/admin/products',p.key]">Edit</a></td>
</tbody>
</table>
From your html code, I think you need a array of object.
for example :
array = [
{key: 'key1', title: 'title 1', price: 10, },
{key: 'key2', title: 'title 2', price: 10, },
{key: 'key3', title: 'title 3', price: 10, }
]
if my assumption is correct then there are several problems here.
array construction is not ok.
your array variable is local. make it a public variable otherwise from html you can't access it.
In html, you are trying to iterate the array and each iteration, the data will be assigned in your local variable 'p' (as you are using *ngFor="let p of array")
so, change your code to this
import { ProductsService } from './../../products.service';
import { Component, OnInit } from '#angular/core';
import { AngularFireDatabase, AngularFireAction, DatabaseSnapshot } from 'angularfire2/database';
#Component({
selector: 'app-admin-products',
templateUrl: './admin-products.component.html',
styleUrls: ['./admin-products.component.css']
})
export class AdminProductsComponent{
array: any = [];
constructor(
private products:ProductsService,
private db : AngularFireDatabase
) {
products.getAll().on('child_added',function(c){
let data = c.val();
let key = c.key;
let price = data.price;
let title = data.title;
this.array.push({"key":key, "title":title, "price":price });
console.log('array of data', this.array);
})
}
}
and change your html to this,
<table class="table">
<thead>
<th>Title</th>
<th>Price</th>
<th></th>
</thead>
<tbody *ngFor="let p of array">
<td>{{p.title}}</td>
<td>{{p.price}}</td>
<td ><a [routerLink]="['/admin/products',p.key]">Edit</a></td>
</tbody>
</table>
Change this:
<tbody *ngFor="let p of array">
<td>{{array.title}}</td>
<td>{{array.price}}</td>
into this:
<tbody *ngFor="let p of array">
<td>{{p.title}}</td>
<td>{{p.price}}</td>
You have an array of object, therefore you need to use ngFor to iterate inside the array and then use the variable p to access the attribute's values.
Try like this:
Have the loop in tr instead of td
Change {{array.title}} to {{p.title}}
Make array global
.html
<tbody>
<tr *ngFor="let p of array">
<td>{{p.title}}</td>
<td>{{p.price}}</td>
<td ><a [routerLink]="['/admin/products',p.key]">Edit</a></td>
</tr>
</tbody>
.ts
export class AdminProductsComponent{
array:any[] = [];
products.getAll().on('child_added',function(c){
let data = c.val();
let key = c.key;
let price = data.price;
let title = data.title;
this.array=[];
this.array.push({"key":key});
this.array.push({"title":title});
this.array.push({"price":price});
console.log('array of data',this.array);
})
}
array is a local variable inside your callback. Make it a member of your component to make it available in the template.
export class AdminProductsComponent{
array: any[] = [];
constructor(
private products:ProductsService,
private db : AngularFireDatabase
) {
products.getAll().on('child_added', c => {
let data = c.val();
let key = c.key;
let price = data.price;
let title = data.title;
// you probably want one item per product, not three??
this.array.push({ key, title, price });
})
}
}
Template:
<tbody >
<tr *ngFor="let p of array">
<td>{{p.title}}</td>
</tr>
</tbody>
Define an array property in your component and pass objects into it.
Use Arrow function for the on callback so your this context is the component.
import { ProductsService } from './../../products.service';
import { Component, OnInit } from '#angular/core';
import { AngularFireDatabase, AngularFireAction, DatabaseSnapshot } from 'angularfire2/database';
#Component({
selector: 'app-admin-products',
templateUrl: './admin-products.component.html',
styleUrls: ['./admin-products.component.css']
})
export class AdminProductsComponent{
// Define property here
public array = [],
constructor(
private products:ProductsService,
private db : AngularFireDatabase
) {
products.getAll().on('child_added',(c) => {
let data = c.val();
let key = c.key;
let price = data.price;
let title = data.title;
this.array.push({key, title, price});
})
}
}
I've been beating my head up against the wall on this one for a while but I finally feel close. What I'm trying to do is read my test data, which goes to a two dimensional array, and print its contents to a table in the html, but I can't figure out how to use an ngfor to loop though that dataset
Here is my typescript file
import { Component } from '#angular/core';
import { Http } from '#angular/http';
#Component({
selector: 'fetchdata',
template: require('./fetchdata.component.html')
})
export class FetchDataComponent {
public tableData: any[][];
constructor(http: Http) {
http.get('/api/SampleData/DatatableData').subscribe(result => {
//This is test data only, could dynamically change
var arr = [
{ ID: 1, Name: "foo", Email: "foo#foo.com" },
{ ID: 2, Name: "bar", Email: "bar#bar.com" },
{ ID: 3, Name: "bar", Email: "bar#bar.com" }
]
var res = arr.map(function (obj) {
return Object.keys(obj).map(function (key) {
return obj[key];
});
});
this.tableData = res;
console.log("Table Data")
console.log(this.tableData)
});
}
}
Here is my html which does not work at the moment
<p *ngIf="!tableData"><em>Loading...</em></p>
<table class='table' *ngIf="tableData">
<tbody>
<tr *ngFor="let data of tableData; let i = index">
<td>
{{ tableData[data][i] }}
</td>
</tr>
</tbody>
</table>
Here is the output from my console.log(this.tableData)
My goal is to have it formatted like this in the table
1 | foo | bar#foo.com
2 | bar | foo#bar.com
Preferably I'd like to not use a model or an interface because the data is dynamic, it could change at any time. Does anyone know how to use the ngfor to loop through a two dimensional array and print its contents in the table?
Like Marco Luzzara said, you have to use another *ngFor for the nested arrays.
I answer this just to give you a code example:
<table class='table' *ngIf="tableData">
<tbody>
<tr *ngFor="let data of tableData; let i = index">
<td *ngFor="let cell of data">
{{ cell }}
</td>
</tr>
</tbody>
</table>
I have a component.
#Component({
selector: 'top3',
templateUrl: 'dev/templates/top3.html',
pipes: [orderBy],
providers: [HTTP_PROVIDERS, ParticipantService]
})
export class AppTop3Component implements OnInit {
constructor (private _participantService: ParticipantService) {}
errorMessage: string;
participants: any[];
ngOnInit() {
this.getParticipants();
}
getParticipants() {
this._participantService.getParticipants()
.then(
participants => this.participants = participants,
error => this.errorMessage = <any>error
);
}
}
This component use a service, named _participantService. The _participantService retrieves an array of objects. I output my array of objects in component`s template:
<h2>Top 3</h2>
<table class="table table-bordered table-condensed" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Score</th>
</tr>
</thead>
<tbody>
<tr *ngFor="#participant of participants | orderBy: '-score'; #i = index">
<td>{{i+1}}</td>
<td>{{participant.username}}</td>
<td>{{participant.score}}</td>
</tr>
</tbody>
</table>
I use a Pipe, named orderBy with *ngFor directive. The problem is when I don`t use a Pipe and output array in this way:
<tr *ngFor="#participant of participants; #i = index">
everything is OK, and I've got a correct result:
But when I want to sort my object's array and use my Pipe, I don't have any output:
I`ve got an undefined object in my Pipe function^
#Pipe({
name: 'orderBy',
pure: false
})
export class orderBy implements PipeTransform {
transform(arr: any[], orderFields: string[]): any {
console.log(arr);
orderFields.forEach(function(currentField: string) {
var orderType = 'ASC';
if (currentField[0] === '-') {
currentField = currentField.substring(1);
orderType = 'DESC';
}
arr.sort(function(a, b) {
return (orderType === 'ASC') ?
(a[currentField] < b[currentField]) ? -1 :
(a[currentField] === b[currentField]) ? 0 : 1 :
(a[currentField] < b[currentField]) ? 1 :
(a[currentField] === b[currentField]) ? 0 : -1;
});
});
return arr;
}
}
Since you load your data asynchronously using a promise, they are null at the beginning (before the first callback defined in the then method is called).
You need to check if the are parameter is null in your pipe. If so you shouldn't execute the "order by" processing...
When the result will be there, the pipe will be called again with the data (are won't be null). In this case, you will be able to sort data...
You could try this code:
#Pipe({
name: 'orderBy',
pure: false
})
export class orderBy implements PipeTransform {
transform(arr: any[], orderFields: string[]): any {
if (arr==null) {
return null;
}
(...)
}
}
According to an example of the doc of the Pipes (https://angular.io/docs/ts/latest/guide/pipes.html#!#jsonpipe), you missed parenthesis :
<tr *ngFor="#participant of (participants | orderBy: '-score'); #i = index">
Instead of modifying your pipe implementation to handle null (i.e., #Thierry's answer), you could instead simply define an empty array in your component:
participants = [];
When the data comes back from the server, either push items onto the existing array,
.then(participants => this.participants.push(...participants),
or do what you already do: assign a new array.
Note that ... is an ES2015 feature.