How can I make Angular model work in html page? - html

I connect with my service without any problem, then I import it into a model, but when I try to print the data with a for loop in the html page, it comes up blank. Where do you think I am doing wrong?
this is component file
import { Component, OnInit, ViewChild } from '#angular/core';
import { ResultsModel } from 'src/app/core/models/results.model';
#Component({
selector: 'app-results',
templateUrl: './results.component.html',
styleUrls: ['./results.component.scss']
})
export class ResultsComponent implements OnInit {
clientResults : ResultsModel[] = [];
constructor(private httpRequestService : HttpRequestService) {}
ngOnInit(): void {
this.getAllResults();
}
getAllResults(){
let apiEndpoint = "results"
this.httpRequestService.getApi(apiEndpoint, false).subscribe(resultRequest => {
this.clientResults = resultRequest
return this.clientResults
})
}
this is model file
export interface ResultsModel {
"result": string,
"createddate": string,
"clientid": string,
"id": number,
"clientusername": string,
}
this is html file
<table class="table align-middle table-nowrap" id="invoiceTable">
<thead class="text-muted">
<tr>
<th class="sort text-uppercase" data-sort="invoice_id">User Id</th>
<th class="sort text-uppercase" data-sort="customer_name">Username</th>
<th class="sort text-uppercase" data-sort="email">Type</th>
<th class="sort text-uppercase" data-sort="date">Type</th>
<th class="sort text-uppercase" data-sort="invoice_amount">Type</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let results in clientResults">
<td>{{results.id}}</td>
<td class="customer_name">{{results.username}}</td>
<td>{{results.clientid}}</td>
<td>{{results.result}}</td>
<td>{{results.createddate}}</td>
</tr>
</tbody>
</table>
Where do you think I went wrong? Where could I be doing wrong?

Related

Put json data into table

I actually want to create a table with the data who the api return to me.
The problem is that i can't print the data.
The IdLangage have his column in the table and i want to put the data of the traduction into the correct cell.
The JSON data format :
traductionData ={
"Data":
[
{
"Code": "BJR",
"TraductionsFormat":
[{
"Code": "BJR",
"Description": null,
"Id": 0,
"IdLangage": "FR",
"Traduction": "Bonjour"
},
{
"Code": "BJR",
"Description": null,
"Id": 0,
"IdLangage": "EN",
"Traduction": "Hello"
}]
},
] };
Here is my table where i want to print the data into :
<table>
<thead>
<tr>
<th width="25%">Code</th>
<th width="15%">FR</th>
<th width="15%">EN</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let traduction of traductionData">
<td>{{ traduction.TraductionsFormat.Code }}</td>
<td>{{ traduction.TraductionsFormat.Traduction}}</td>
</tr>
</tbody>
</table>
Here is my angular service :
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http'
import { map } from 'rxjs/operators';
import { environment } from 'src/environments/environment';
#Injectable({
providedIn: 'root'
})
export class ApiService {
localUrlAPI: string = environment.urlAPI;
constructor(private http : HttpClient) { }
getAllTraductions(){
return this.http.get<any>(this.localUrlAPI+"GetAllTraductionsGroupByCode")
.pipe(map((res:any)=>{
return res;
console.log(res);
}))
}
}
And here is my angular Component with my http request :
import { Component, OnInit } from '#angular/core';
import { ApiService } from 'src/app/services/api.service';
#Component({
selector: 'app-grid-edit-traductions',
templateUrl: './grid-edit-traductions.component.html',
styleUrls: ['./grid-edit-traductions.component.scss']
})
export class GridEditTraductionsComponent implements OnInit {
traductionData !: any[];
constructor(private api: ApiService) { }
ngOnInit(): void {
this.getLesTraductions();
}
getLesTraductions(){
this.api.getAllTraductions()
.subscribe(res=>{
this.traductionData = res.Data;
console.log(this.traductionData)
})
}
}
<table>
<thead>
<tr>
<th *ngFor="let column of tableHeaders">
{{column}}
</th>
</tr>
</thead>
<tbody>
<tr ng *ngFor="let row of tableRows">
<td *ngFor="let column of tableHeaders">
{{row[column]}}
<ng-container *ngFor="let trad of row.TraductionsFormat, let j = index">
<span *ngIf="row.TraductionsFormat[j].IdLangage === column">
{{row.TraductionsFormat[j].Traduction}}
</span>
</ng-container>
</td>
</tr>
</tbody>
</table>
Here's the ts:
tableRows: Array<any> = [];
tableHeaders: Array<any> = [];
ngOnInit(): void {
//---- TABLE HEADERS -----
this.tableHeaders.push("Code")
this.traductionData.Data.forEach(el => {
el.TraductionsFormat.map(c => c.IdLangage).forEach(lang => {
this.tableHeaders.push(lang);
})
});
this.tableHeaders = [...new Set(this.tableHeaders)];
//---- TABLE ROWS -----
this.traductionData.Data.forEach(el => {
this.tableRows.push(el)
});
}
Stackblitz example
The JSON data you've provided is wrong, there are missing commas and brackets. Although, I'm pretty sure that the reason the data isn't shown in table is that the "TraductionsFormat" is an array. If you want to get an item from array you have to provide an index.
<tr *ngFor="let traduction of traductionData">
<td>{{ traduction.TraductionsFormat[0].Code }}</td>
<td>{{ traduction.TraductionsFormat[0].Traduction}}</td>
</tr>
Above is just simple solution. You might want to use dynamic indexes.

i have user adding form, each user has delete button. how can i make it delete it's user?

user.model.ts // interface for user
export interface User {
id:number,
firstName:string,
lastName:string,
eMail:string
}
form.component.ts
import { Component, OnInit } from '#angular/core';
import { User } from '../interfaces/user.model';
#Component({
***
})
export class FormComponent implements OnInit {
idNumber: number = 0;
userInfo: User[] = [];
constructor() { }
addUser(firstname: HTMLInputElement, lastname: HTMLInputElement, email: HTMLInputElement) {
this.idNumber += 1;
this.userInfo.push({ id: this.idNumber, firstName: firstname.value, lastName: lastname.value, eMail: email.value });
console.log(this.userInfo)
***
}
ngOnInit(): void {
}
}
table.component.ts
import { Component, OnInit, Input } from '#angular/core';
#Component({
***
})
export class TableComponent implements OnInit {
#Input() users:any;
constructor() { }
ngOnInit(): void {
}
}
table.component.html
there is a delete button for each user I add. I want them to delete users which belong to them. is it possible to pass the user index?
<table class="ui celled table">
<thead>
***
</thead>
<tbody>
<tr *ngFor="let user of users">
<td>{{user.id}}</td>
<td>{{user.firstName}}</td>
<td>{{user.lastName}}</td>
<td>{{user.eMail}}</td>
<td style="width: 40px;" ><button class="delButton"><i class="times icon"></i></button></td>
</tr>
</tbody>
</table>
Try following code
<table class="ui celled table">
<thead>
***
</thead>
<tbody>
<tr *ngFor="let user of users;let i = index">
<td>{{user.id}}</td>
<td>{{user.firstName}}</td>
<td>{{user.lastName}}</td>
<td>{{user.eMail}}</td>
<td style="width: 40px;" ><button class="delButton" (click)="deleteUser(i)"><i class="times icon"></i></button></td>
</tr>
</tbody>
And inside the table.component.ts file add the following function
deleteUser(index: number) { this.users.splice(index, 1); }

How to hide the full row if any cell value is null in angular

I would like to hide the row for the while payment due date cell is empty for the respective row.
while any value of Payment Due Date is null or empty I would like to hide the whole row respectively.
user.service.ts
import { Injectable } from '#angular/core';
import { HttpClient} from '#angular/common/http'
#Injectable({
providedIn: 'root'
})
export class UsersService {
constructor( private http:HttpClient) { }
getData(){
let url="https://Test.azurewebsites.net/api/accounts/getall";
return this.http.get(url);
}
}
app.component.ts
import { analyzeAndValidateNgModules } from '#angular/compiler';
import { Component } from '#angular/core';
import { UsersService} from './users.service'
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'coding-test';
data : any
constructor( private user:UsersService){
this.user.getData().subscribe(data=>{
console.warn(data)
this.data = data
})
}
}
app.component.html
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="display-6">Display Sorted Account Info</h1>
<table class="table table-striped" >
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th >Amount Due</th>
<th>Payment Due Date</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of data" >
<td>{{item.LastName}},{{item.FirstName}}</td>
<td>{{item.Email}}</td>
<td>{{item.PhoneNumber | phone}}</td>
<td>{{item.AmountDue | currency}}</td>
<td>{{item.PaymentDueDate | date}}</td>
</tr>
</tbody>
</table>
</div>
</div>
on app.component.ts you can add filter by changing ((this.data = data )) to :
this.data = data.filter(x=>x.PaymentDueDate !== null );
Try to filter out the object based on the condition in your ts file.This will solve your problem.

How to bind Json response to table

I have products.components.ts class, where I am getting Json data in this.Getdata
ngOnInit() {
this._service.getProducts(this.baseUrl)
.subscribe(data => {
this.Getdata=data
this.products=data
alert(JSON.stringify(this.Getdata));
});
This Josn data I want to bind in products.components.html class Table
<p>
Product List
</p>
<table>
<th>Id</th> <th>Name</th> <th> Country</th> <th>Actions</th>
<tr *ngFor="let lst of products; let i = index" border="1">
<td>{{i+1}}</td><td>{{lst.id}}</td><td>{{lst.employee_name}}</td> <td>Edit</td>
</tr>
</table>
The above code is not working. Only alert displaying. How can I bind data to table?
This is my Json data
[{"id":"1","employee_name":"amit","employee_salary":"0","employee_age":"0","profile_image":""},{"id":"247793","employee_name":"Ana","employee_salary":"123","employee_age":"123","profile_image":""},{"id":"247856","employee_name":"Joseph Beltran","employee_salary":"1000","employee_age":"23","profile_image":""},{"id":"247982","employee_name":"testyeyyeye1","employee_salary":"123","employee_age":"23","profile_image":""},{"id":"248007","employee_name":"test100","employee_salary":"123","employee_age":"23","profile_image":""},{"id":"248038","employee_name":"Hendry","employee_salary":"61888","employee_age":"26","profile_image":""}]
Model class
export class Productlist {
id: string;
employee_name: string;
employee_salary: string;
employee_age: string;
profile_image: string;
}
Instead of subscribing to the Observable, consider storing it in a property and then unwrapping it in the template using the async pipe.
If you consider that, then you can significantly reduce your Component to this:
import { Component } from '#angular/core';
import { Observable } from 'rxjs';
import { EmployeeService } from './employee.service';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
employees$: Observable<Array<any>> = this.employeeService.getEmployees();
constructor(private employeeService: EmployeeService) {}
}
And in your Template:
<p>
Employee List
</p>
<table border="1">
<thead>
<th>Id</th>
<th>Name</th>
<th> Country</th>
<th>Actions</th>
</thead>
<tbody>
<tr *ngFor="let employee of employees$ | async; let i = index">
<td>{{i+1}}</td>
<td>{{employee.id}}</td>
<td>{{employee.employee_name}}</td>
<td>Edit</td>
</tr>
</tbody>
</table>
Here's a Working Sample Demo Code for your ref.
PS: Consider naming your properties and methods appropriately. If you're working with employees, then it doesn't really make sense to name properties and methods as products.
You can also use
const myobject= JSON.parse(yourjsonvalue);
You will get the object in myobject and now you can loop through with simple ngFor.
I got it this way
export class ProductsComponent implements OnInit {
public Getdata;
products:Productlist[];
constructor(private employeeService: ProductService) {}
ngOnInit() {
this.employeeService.getProducts(this.baseUrl)
.subscribe((data:any) => {
this.products=data;
});
}
}

Angular 4 : Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays

I want to show the data from my backend (CodeIgniter) to my frontend (Angular 4),
but this error come up:
ERROR Error: Cannot find a differ supporting object '[object Object]' of type > 'object'. NgFor only supports binding to Iterables such as Arrays.
This is my component:
import { BookService } from './../book.service';
import { Component, OnInit } from '#angular/core';
import { Book } from "../book";
#Component({
selector: 'app-book',
templateUrl: './book.component.html',
styleUrls: ['./book.component.css']
})
export class BookComponent implements OnInit {
constructor(public bookService: BookService ) { }
ngOnInit() {
this.getBooks();
}
books:Book;
getBooks(){
this.bookService.getBooks()
.subscribe(books=>{
this.books = books;
})
}
}
This is my service:
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map' ;
#Injectable()
export class BookService {
constructor(private http: Http) {
}
books=[];
getBooks(){
return this.http.get("http://localhost/restserver/book/list_book.php")
.map(res => res.json());
}
}
My .json:
{"status":true,"data":
[{"id":"1","title":"SAINS","author":"ERLANGGA","isbn":"089928778"},
{"id":"2","title":"Geography","author":"ERLANGGA","isbn":"089182372"},
{"id":"3","title":"Math","author":"Srilangka","isbn":"091283181"},
{"id":"4","title":"test","author":"test","isbn":"1283798127"},
{"id":"5","title":"AAAA","author":"BBB","isbn":"91092301290"},
{"id":"6","title":"BBB","author":"CCC","isbn":"01920192"}]}
And this is my view:
<div class="container-fluid">
<div class="row">
<div class="card col-md-7">
<div class="card-body">
<table class="table table-responsive table-striped">
<caption>List of Books</caption>
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Title</th>
<th scope="col">Author</th>
<th scope="col">ISBN</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let book of books" >
<th></th>
<td>{{book.title}}</td>
<td>{{book.author}}</td>
<td>{{book.isbn}}</td>
<td>
<button class="btn btn-primary "> Detail </button>
<button class="btn btn-success " [routerLink]="['/book-edit']"> Edit </button>
<button class="btn btn-danger "> Delete </button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<app-book-add class="col-md-5"></app-book-add>
Issue :
You are assigning the whole response to books , but all you need is
data.
1) First way to solve it
Change this line from in component:
this.books = books;
to
this.books = books.data;
2) Or you can also do this in template:
Change this :
<tr *ngFor="let book of books" >
to
<tr *ngFor="let book of books?.data" >
books should be collection of Book & then set data property of returned response.
books:Book[]; //this should be change inside Component.
//service method should return data prop from it.
getBooks(){
return this.http.get("http://localhost/restserver/book/list_book.php")
.map(res => res.json().data);
}