This question already has answers here:
JQuery - $ is not defined
(36 answers)
Closed 4 years ago.
I'm trying to add Paging and sorting to my table but I got this error , howerver I follow all the steps which listed here
http://l-lin.github.io/angular-datatables/#/getting-started.
I already check the previous problem but I did't work with me
I install all its dependencies
Here's the code of the component :-
import { Component, OnInit, OnDestroy } from '#angular/core';
import { ProductService } from '../../service/product-service.service';
import { Subscription, Subject } from 'rxjs';
#Component({
selector: 'app-admin-products',
templateUrl: './admin-products.component.html',
styleUrls: ['./admin-products.component.css']
})
export class AdminProductsComponent implements OnInit, OnDestroy {
products: any[];
filteredProducts: any[];
subscribtion: Subscription;
dtOptions: DataTables.Settings = {};
dtTrigger: Subject<any> = new Subject();
constructor(private productService: ProductService) {
this.subscribtion = productService.getAll().
// We take a copy of Products and Assigned to filteredProducts
subscribe(
products => {
this.filteredProducts = this.products = products;
this.dtTrigger.next();
}
);
}
ngOnInit() {
this.dtOptions = {
pagingType: 'full_numbers',
pageLength: 5,
processing: true
};
}
filter(queryStr: string) {
// console.log(this.filteredProducts);
if (queryStr) {
this.filteredProducts = this.products.
filter(p => p.payload.val().title.toLowerCase().includes(queryStr.toLowerCase()));
} else {
this.filteredProducts = this.products;
}
}
ngOnDestroy(): void {
// to UnSubscribe
this.subscribtion.unsubscribe();
}
}
Here's the code of the the HTML :-
I follow also all the steps here
<p>
<a routerLink="/admin/products/new" class="btn btn-primary">New Product</a>
</p>
<p>
<input type="text"
#query
(keyup)="filter(query.value)"
placeholder="Search ..." class="form-control">
</p>
<table
datatable [dtOptions]="dtOptions"
[dtTrigger]="dtTrigger" class="table" >
<thead class="thead-dark">
<tr>
<th scope="col">Title</th>
<th scope="col">Price</th>
<th scope="col">Edit</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let product of filteredProducts">
<td>{{ product.payload.val().title }}</td>
<td>{{ product.payload.val().price }}</td>
<td>
<a [routerLink]="['/admin/products/', product.key]">Edit</a>
</td>
</tr>
</tbody>
</table>
$ not defined mostly means you are not including JQuery.
try adding: to your program
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" type="text/javascript"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js" type="text/javascript"></script>
source
Related
I am getting below error even by adding. can someone guide me or make some code changes so that the program executes as expected
Error: src/app/product/product.component.html:21:45 - error TS2367: This condition will always return 'true' since the types 'Observable<Product[]>' and 'number' have no overlap.
21 <table class = "table table-hover" *ngIf = "products != 0">
~~~~~~~~~~~~~
src/app/product/product.component.ts:9:16
9 templateUrl: './product.component.html',
~~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component ProductComponent.
import { Component, OnInit } from '#angular/core';
import { Product } from './product.model';
import { Store } from '#ngrx/store';
import { Observable } from 'rxjs';
import { AppState } from './../app.state';
#Component({
selector: 'app-product',
templateUrl: './product.component.html',
styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {
products : Observable<Product[]>;
constructor(private store: Store<AppState>) {
this.products = this.store.select(state => state.product)
}
addProduct(name: any, price: any){
this.store.dispatch({
type : 'ADD_PRODUCT',
payload : <Product>{
name : name,
price : price
}
});
}
ngOnInit(): void {
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<table class = "table table-hover" *ngIf = "products != 0">
<thead>
<tr>
<td>Product Name</td>
<td>Product Price</td>
</tr>
</thead>
<tbody>
<tr *ngFor = "let product of products | async">
<td></td>
<td></td>
</tr>
</tbody>
</table>
You are missing something here
<table class = "table table-hover" *ngIf = "products != 0">
The error tells you that the condition its going to be always true because products is of type Observable<Product[]> and 0 is a number, and obviously they are diferent.
Maybe you want to go with this
<table class = "table table-hover" *ngIf = "(products | async).length != 0">
Here the condition is asking if the length of the array returned by the Observable products is not 0. You can use the someObservable | async when you want to retrieve the value emitted by an Observable in the template.
I am developing a Angular website with help of Firebase Firestore. It is my first project on Angular. I have learned Angular 2months ago. Please See the below codes: -
Component.html
<section class="rank">
<p class="records" *ngIf="members.length === 0">No Records Found.</p>
<div class="text-img" *ngIf="members.length > 0">
<p class="sb">Best Sulphuric</p>
<p class="role">Member</p>
<p class="name">
{{ members[0].payload.doc.data().name }}
</p>
</div>
<table *ngIf="members.length > 0">
<tr>
<th>ID</th>
<th>Name</th>
<th>Posts</th>
<th>Score</th>
</tr>
<tr *ngFor="let member of members; let indexOfelement = index">
<td>{{ indexOfelement + 1 }}</td>
<td>{{ member.payload.doc.data().name }}</td>
<td>{{ member.payload.doc.data().posts }}</td>
<td>{{ member.payload.doc.data().score }}</td>
</tr>
</table>
</section>
Component.ts
import { Component, OnInit } from '#angular/core';
import { AngularFirestore } from '#angular/fire/firestore';
#Component({
selector: 'app-rank',
templateUrl: './rank.component.html',
styleUrls: ['./rank.component.scss'],
})
export class RankComponent implements OnInit {
members: any;
constructor(public db: AngularFirestore) {
db.collection('members')
.snapshotChanges()
.subscribe((res) => (this.members = res));
}
ngOnInit(): void {}
}
When I open this on browser this shows all the data in members in Firestore. But when i change component.ts to this -->
Component.ts
import { Component, OnInit } from '#angular/core';
import { AngularFirestore } from '#angular/fire/firestore';
#Component({
selector: 'app-rank',
templateUrl: './rank.component.html',
styleUrls: ['./rank.component.scss'],
})
export class RankComponent implements OnInit {
members: any;
constructor(public db: AngularFirestore) {
this.members = db.collection('members').ref.orderBy('score');
}
ngOnInit(): void {}
}
It shows no data on window. Can you help me please?
Thanks in Advance for Helping.
In the second version,
You are missing the
.snapshotChanges()
.subscribe((res) => (this.members = res));
}
inside the constructor. Without the subscribe, Angular will not make any HTTP Requests and your component will not receive any data.
I'm new to OOP and angular.
currently, I want to use reusable table with pagination that makes a request API if page change (pagination inside table component).
the problem is when I access my method using callback from table component (Child) I got undefined.
but when I try to move pagination to MasterGudang (Parent) Components it's work.
I don't really understand what's going on.
Error undefined
but here some code.
table.component.ts
import { Subject } from 'rxjs';
#Component({
selector: 'ngx-table-custom',
templateUrl: './table.component.html',
styleUrls: ['./table.component.scss']
})
export class TableComponent implements OnInit {
constructor() { }
#Input() items: any;
#Input() callback: any;
#Input() columns: [];
p: number = 1;
#ContentChild('action', { static: false }) actionRef: TemplateRef<any>;
ngOnInit(): void {
this.items = new Subject();
this.items.next();
}
onChangePage = (evt) => {
this.callback()
}
Gudang.component.ts
import { MasterGudangService } from '../../../../#core/services/master-service/menu-gudang/gudang/masterGudang.service';
#Component({
selector: "ngx-gudang",
templateUrl: './gudang.component.html',
styleUrls: ['./gudang.component.scss'],
})
#Injectable({
providedIn: 'root'
})
export class GudangComponent implements OnInit {
constructor(
public masterGudangService: MasterGudangService
) {
console.log(masterGudangService)
}
tableData: [];
isEdit: boolean = false;
currentPage: number = 1;
ngOnInit(): void {
this.getList();
}
getList (page?: number) {
this.masterGudangService.getPgb(page? page: this.currentPage).subscribe(response => {
const { data: { content, totalElements, size, number } } = response;
this.tableData = Object.assign({
data: content,
total: totalElements,
size: size,
number: number
});
});
}
}
And here I passing my function which is getList to table component
gudang.component.html
<ngx-table-custom [callback]="getList" [columns]="column" [items]="tableData">
<ng-template let-item #action>
<div class="row">
<button nbButton status="success" (click)="open(dialog, item, true)" class="mx-2" size="tiny"><nb-icon icon="edit"></nb-icon></button>
<button nbButton status="danger" (click)="onDelete(item)" size="tiny"><nb-icon icon="trash"></nb-icon></button>
</div>
</ng-template>
</ngx-table-custom>
MasterGudangService.ts
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
#Injectable({
providedIn: 'root'
})
export class MasterGudangService {
constructor(private http: HttpClient) { }
getPgb (page: number = 1, perPage: number = 10) :any {
return this.http.get(`my-api-url/pgb?page=${page}&size=${perPage}`)
}
}
table.component.html
<div class="row">
<div class="col-12">
<table class="table table-md table-striped">
<thead>
<tr style="background-color: #3366ff; color: #fff;">
<th *ngFor="let column of columns" class="text-basic">{{ column.value }}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of items.data | paginate: { itemsPerPage: 10, currentPage: p, totalItems: items.total }; index as idx;">
<td *ngFor="let column of columns">
<div *ngIf="column.key === 'number';"><b class="text-basic">{{ idx + 1 }}</b></div>
<div *ngIf="column.key !== 'action' && !isNested(column.key);" class="text-basic">{{ item[column.key] }}</div>
<div *ngIf="isNested(column.key);" class="text-basic">{{ getKeys(item, column.key) }}</div>
<!-- <div *ngIf="column.key === 'action; action_container"></div> -->
<ng-template [ngIf]="column.key === 'action'" #action_content>
<ng-container
*ngIf="actionRef"
[ngTemplateOutlet]="actionRef"
[ngTemplateOutletContext]="{$implicit:item}">
</ng-container>
</ng-template>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="row">
<div class="col-12" align="center">
<pagination-controls (pageChange)="onChangePage($event)"></pagination-controls>
</div>
</div>
The context of Gudang.component.ts will not be available using callback from table component.
The proper way to implement should be passing the event instead of passing function for callback
table.component.ts
#Output() pageChange = new EventEmitter()
onChangePage = (evt) => {
this.pageChange.emit(evt);
}
gudang.component.html
<ngx-table-custom (pageChange)="getList($event)" [columns]="column" [items]="tableData">
...
</ngx-table-custom>
based on the error, it seems like masterGudangService is null at the time you are trying to access it. Adding this code might help you eliminate the error and at least debug what is going on and get a step further.
ngOnInit(): void {
if(this.masterGudangService)
this.getList();
else
console.log('service not defined!');
}
You could define a helper Method in GudangComponent
getListCallback() {
return this.getList.bind(this);
}
and use it here
<ngx-table-custom [callback]="getListCallback()" [columns]="column" [items]="tableData">
I'm building my first Angular app and I'm trying to integrate firestore.
So far I was able to retrieve data from firestore and also log the id with snapshot but I'm not being able to bring it all together.
Is there a way to add the id to the client Model?
I was reading the angularfire2 documentation where it says that we can't use the $key property and now we should use snapshot but I can't figure it out.
Thanks
This is my Service
#Injectable()
export class ClientService {
clientsCollection: AngularFirestoreCollection<Client>;
clients: Observable<Client[]>;
snapshot: any;
constructor(private afs: AngularFirestore) {
this.clientsCollection = this.afs.collection('clients');
this.clients = this.clientsCollection.valueChanges();
// snapshot for id/metadata
this.snapshot = this.clientsCollection.snapshotChanges()
.map(arr => {
console.log(arr);
});
}
}
My client.component.ts
#Component({
selector: 'app-clients',
templateUrl: './clients.component.html',
styleUrls: ['./clients.component.css']
})
export class ClientsComponent implements OnInit {
clients: Client[];
snapshots: any[];
constructor(
public clientService: ClientService
){}
ngOnInit(){
this.clientService.clients.subscribe(clients => {
this.clients = clients;
});
}
}
And my client.component.html
<table *ngIf="clients?.length > 0; else noClients" class="table table-striped">
<thead class="thead-inverse">
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Balance</th>
<th></th>
</tr>
</thead>
<tbody>
<tr *ngFor="let client of clients">
<td></td>
<td>{{ client.firstName }} {{ client.lastName }}</td>
<td>{{ client.email }}</td>
<td>{{ client.balance }}</td>
<td>Details</td>
</tr>
</tbody>
</table>
<ng-template #noClients>
<hr>
<h5>There are no clients in the system</h5>
</ng-template>
this is what I have so far
You can find answer in angularfire2 documents
export class AppComponent {
private shirtCollection: AngularFirestoreCollection<Shirt>;
shirts: Observable<ShirtId[]>;
constructor(private readonly afs: AngularFirestore) {
this.shirtCollection = afs.collection<Shirt>('shirts');
// .snapshotChanges() returns a DocumentChangeAction[], which contains
// a lot of information about "what happened" with each change. If you want to
// get the data and the id use the map operator.
this.shirts = this.shirtCollection.snapshotChanges().map(actions => {
return actions.map(a => {
const data = a.payload.doc.data() as Shirt;
const id = a.payload.doc.id;
return { id, ...data };
});
});
}
}
and this template
<ul>
<li *ngFor="let shirt of shirts | async">
{{ shirt.id }} is {{ shirt.price }}
</li>
</ul>
I have a simple component in my angular2 app:
#Component({
selector: 'app-product',
templateUrl: './product.component.html',
styleUrls: ['./product.component.css'],
providers: [ProductService, CardService]
})
export class ProductComponent implements OnInit {
private products;
constructor(private productService: ProductService, private cartService: CartService) {
}
ngOnInit() {
this.loadProducts();
}
loadProducts() {
this.productService.getProducts().subscribe(data => this.products = data);
}
addProductToCart(product: Product) {
this.cartService.addProduct(product);
}
basketAmount() {
this.cartService.getNumberOfProducts();
}
html file connected to it:
<div class="basket">
On your card: {{basketAmount()}}
</div>
<table class="table table-striped">
<thead class="thead-inverse">
<tr>
<th>#</th>
<th>Name</th>
<th>Desc</th>
<th>Price</th>
<th>Amount</th>
</tr>
</thead>
<tbody *ngFor="let product of products">
<tr>
<th scope="row">{{product.id}}</th>
<td>{{product.name}}</td>
<td>{{product.description}}</td>
<td>{{product.price}}</td>
<td>{{product.amount}}</td>
<button type="button" class="btn btn-success" (click)="addProductToCart(product)">Add to cart</button>
</tr>
</tbody>
</table>
and CartService
#Injectable()
export class CardService {
private cart: Product[] = [];
constructor() {
}
addProduct(product: Product) {
this.cart.push(product);
}
getTotalPrice() {
const totalPrice = this.cart.reduce((sum, cardItem) => {
return sum += cardItem.price, sum;
}, 0);
return totalPrice;
}
getNumberOfProducts() {
const totalAmount = this.card.reduce((sum, cardItem) => {
return sum += cardItem.amount, sum;
}, 0);
return totalAmount;
}
}
export interface Product {
id: number;
name: string;
description: string;
price: number;
amount: number;
}
I would like to update the number of items on my cart after added something into cart and show it on the view. I add items to cart by click and call addProductToCart method. At the same time I want to update a number of this items by basketAmount() which is defined in CartService and return number of items on the cart. I think I should trigger this basketAmount() method in a some way but I do not know how.
How to do it in a good way?
You have multiple options
After pushing item in your cart just call the basketAmount method again and you should have new value.
You can use BehaviorSubject. In this case you just need to subscribe to it and each time you will push the item to cart it will automatically update your cart.
Ok, I found a solution.
I add a simple numberOfItems variable into ProductComponent:
export class ProductComponent implements OnInit {
private products;
private numberOfItems;
constructor(private productService: ProductService, private cardService: CardService) {
}
ngOnInit() {
this.loadProducts();
}
loadProducts() {
this.productService.getProducts().subscribe(data => this.products = data);
}
addProductToCard(product: Product) {
this.cardService.addProduct(product);
}
basketAmount() {
this.numberOfItems = this.cardService.getNumberOfProducts();
}
}
and on the view I call two methods after click and update numberOfItems:
<div class="basket">
On your card: {{numberOfItems}}
</div>
<table class="table table-striped">
<thead class="thead-inverse">
<tr>
<th>#</th>
<th>Name</th>
<th>Desc</th>
<th>Price</th>
<th>Amount</th>
</tr>
</thead>
<tbody *ngFor="let product of products">
<tr>
<th scope="row">{{product.id}}</th>
<td>{{product.name}}</td>
<td>{{product.description}}</td>
<td>{{product.price}}</td>
<td>{{product.amount}}</td>
<button type="button" class="btn btn-success" (click)="addProductToCard(product); basketAmount()">Add to card</button>
</tr>
</tbody>
</table>