I am working on an Angular 2 project. I am trying to add data-table component in my project. But facing above error at the time of compilation.what needs to be done to get the required output. please guide me in a right direction.
admin-products.component.ts
import { Component, OnInit, OnDestroy } from '#angular/core';
import { ProductService } from 'src/app/product.service';
import { Subscription } from 'rxjs';
import { Product } from 'src/app/models/product';
import { DataTableResource } from 'angular-4-data-table';
#Component({
selector: 'app-admin-products',
templateUrl: './admin-products.component.html',
styleUrls: ['./admin-products.component.css']
})
export class AdminProductsComponent implements OnInit,OnDestroy {
products: Product[];
filteredProducts: any[];
subscription: Subscription;
tableResource:DataTableResource<Product>;
items: Product[] = [];
itemCount: Number;
constructor(private productService:ProductService) {
this.subscription = this.productService.getAll().
subscribe(products =>{
this.filteredProducts= this.products = products;
this.initializeTable(products);
});
}
private initializeTable(products:Product[]){
this.tableResource.query({ offset:0})
.then(items => this.items = items);
this.tableResource.count()
.then(count => this.itemCount = count);
}
reloadItems(params){
if(!this.tableResource) return;
this.tableResource.query(params)
.then(items => this.items = items);
}
filter(query: string){
this.filteredProducts = (query) ?
this.products.filter(p => p.title.toLowerCase().includes(query.toLowerCase())) :
this.products;
}
ngOnDestroy(){
this.subscription.unsubscribe()
}
ngOnInit() {
}
}
admin-products.component.html
<p>
<a routerLink="/admin/products/new" class="btn btn-primary">New Product</a>
</p>
<p>
<input
#query
(keyup)="filter(query.value)"
type="text" class="form-control" placeholder="Search...">
</p>
<data-table
[items]="items"
[itemCount]="itemCount"
(reload)="reloadItems($event)"
>
<data-table-column
[property]="'title'"
[header]="'title'"
[sortable]="true"
[resizable]="true"
>
<data-table-column
[property]="'price'"
[header]="'Price'"
[sortable]="true"
[resizable]="true"
>
<ng-template #dataTableCell let-item="item">
{{item.price | currency:'USD':true}}
</ng-template>
</data-table-column>
<data-table-column
[property]="'$key'"
>
<ng-template #dataTableCell let-item="item">
<a [routerLink]="['/admin/products', item.$key]">Edit</a>
</ng-template>
</data-table-column>
</data-table>
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import {AngularFireModule} from 'angularfire2';
import {AngularFireDatabaseModule} from 'angularfire2/database';
import {AngularFireAuthModule} from 'angularfire2/auth';
import {RouterModule} from '#angular/router';
import{NgbModule} from '#ng-bootstrap/ng-bootstrap';
import { BsNavbarComponent } from './bs-navbar/bs-navbar.component';
import { HomeComponent } from './home/home.component';
import { ProductsComponent } from './products/products.component';
import { ShoppingCartComponent } from './shopping-cart/shopping-cart.component';
import { CheckOutComponent } from './check-out/check-out.component';
import { OrderSuccessComponent } from './order-success/order-success.component';
import { MyOrdersComponent } from './my-orders/my-orders.component';
import { AdminProductsComponent } from './admin/admin-products/admin-products.component';
import { AdminOrdersComponent } from './admin/admin-orders/admin-orders.component';
import { LoginComponent } from './login/login.component';
import {FormsModule} from '#angular/forms';
import {CustomFormsModule} from 'ng2-validation';
import {DataTableModule} from 'angular-4-data-table';
import { AppComponent } from './app.component';
import { environment } from 'src/environments/environment';
import { AuthService } from './auth.service';
import { AuthGuard as AuthGuard } from './auth-guard.service';
import { UserService } from './user.service';
import { AdminAuthGuard as AdminAuthGuard } from './admin-auth-guard.service';
import { ProductFormComponent } from './admin/product-form/product-form.component';
import { CategoryService } from './category.service';
import { ProductService } from './product.service';
#NgModule({
declarations: [
AppComponent,
BsNavbarComponent,
HomeComponent,
ProductsComponent,
ShoppingCartComponent,
CheckOutComponent,
OrderSuccessComponent,
MyOrdersComponent,
AdminProductsComponent,
AdminOrdersComponent,
LoginComponent,
ShoppingCartComponent,
ProductFormComponent
],
imports: [
BrowserModule,
FormsModule,
CustomFormsModule,
DataTableModule,
AngularFireModule.initializeApp(environment.firebase),
AngularFireDatabaseModule,
AngularFireAuthModule,
NgbModule.forRoot(),
RouterModule.forRoot([
{path: '', component: HomeComponent},
{path: 'products', component: ProductsComponent},
{path: 'shopping-cart', component: ShoppingCartComponent},
{path: 'login', component: LoginComponent},
{path: 'check-out', component: CheckOutComponent,canActivate:[AuthGuard]},
{path: 'order-success', component: OrderSuccessComponent, canActivate:[AuthGuard]},
{path: 'my/orders',component: MyOrdersComponent,canActivate:[AuthGuard]},
{path: 'admin/products/new', component:ProductFormComponent,canActivate:[AuthGuard,AdminAuthGuard]},
{path: 'admin/products/:id', component:ProductFormComponent,canActivate:[AuthGuard,AdminAuthGuard]},
{path: 'admin/products', component: AdminProductsComponent,canActivate:[AuthGuard,AdminAuthGuard]},
{path: 'admin/orders', component: AdminOrdersComponent,canActivate:[AuthGuard,AdminAuthGuard]}
])
],
providers: [
AuthService,
AuthGuard,
AdminAuthGuard,
UserService,
CategoryService,
ProductService
],
bootstrap: [AppComponent]
})
export class AppModule { }
should be done to get the required output . please guide me in a right direction
This seems to be related to compiler configuration problems. You're trying to add external components and for that you need to make some modifications to your angular project like in your tsconfig.json file. These usually are provided by the library documentation. See this related question for instance: TypeScript error in Angular2 code: Cannot find name 'module'
However, since you're trying to use a table I would highly recommend you some well known Component Libraries for Angular, all of them have well documented and explained examples:
Angular Material(My favorite) - https://material.angular.io/components/table/examples
Prime NG - https://www.primefaces.org/primeng/#/table
If you decide to do that, just follow the Getting Started of any of them and you should be able to use a well built Table Component and more easily find the solution to related bugs.
Related
First is the path in my app routing module
Then the home component
Next is the app component
Lastly the html for button creation
path in the app.routing.module.ts
{
path: 'about-us',
pathMatch: 'full',
data: { type: '', breadcrumb: '' },
component: AboutUsComponent,
},
default constructor and ngOnInit in home.component.ts only router variable in constructor
import { Component, OnInit } from '#angular/core';
import {Router} from '#angular/router';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss'],
})
export class HomeComponent implements OnInit {
constructor(private router : Router) {}
ngOnInit(): void {}
}
default imports in app.module.ts only
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { AboutUsComponent } from './about-us/about-us.component';
import { LoginComponent } from './login/login.component';
import { LogoutComponent } from './logout/logout.component';
import { SocialMediaComponent } from './social-media/social-media.component';
import { LoggedInHomeComponent } from './logged-in-home/logged-in-home.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
#NgModule({
declarations: [
AppComponent,
HomeComponent,
AboutUsComponent,
LoginComponent,
LogoutComponent,
SocialMediaComponent,
LoggedInHomeComponent,
PageNotFoundComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
**button creation code home.component.html**
<div class="about-us">
<button class="button-box" type="button">
<a [routerLink]="'about-us'" [routerLinkActive]="['active']">about-us</a>
</button>
</div>
*My objectives are:
i. Redirect to about us component on click
ii. Open about us component when path is mentioned in url
But neither is working!*
You are missing to import RouterModule from import { RouterModule } from '#angular/router';
Hope you have include RoutingModule in AppRoutingModule. If so try the following code
<a [routerLink]="['about-us']" [routerLinkActive]="['active']">about-us</a>
Have you added router-outlet in
app.component.html file.
Add only above tag & remove everything else from app.component.html if added
Try this & let me know
I successfully used component in routing but when i am using module instead of component in angular 10 i am getting a white screen.
I would be really thankful for any kind of help.
this is what i've been trying:
app-routing.module.ts
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { DashboardModule } from './components/dashboard/dashboard.module';
import { DashboardComponent } from './components/dashboard/dashboard.component';
const routes: Routes = [
{ path: '', loadChildren: () => DashboardModule }
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Dashboard module:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { DashboardComponent } from './dashboard.component';
#NgModule({
declarations: [
DashboardComponent
],
imports: [
CommonModule
]
})
export class DashboardModule { }
Dashboard Component:
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
constructor() {
alert('asdf');
}
ngOnInit(): void {
}
}
Thanks
Lazy loaded feature modules have to have their child routes declared separately. For example:
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { DashboardComponent } from './dashboard.component';
const routes: Routes = [
{
path: '',
component: DashboardComponent,
},
];
#NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class DashboardRoutingModule { }
Also make sure to always load lazy modules like Emilien said before :)
loadChildren: () => import('./components/dashboard/dashboard.module').then(m => m.DashboardModule)
I'm beginner in Angular 9. I'm following an online video tutorial to excercise on angular, but my code (same of the tutorial) had a problem and I don't know of to figure out.
Actually, tutorial put routing stuffs all inside app.module.ts, but I use app-routing.module.ts to separate concerns.
When I launch 'ng serve --open', page still blank with the following error:
core.js:6185 ERROR NullInjectorError: R3InjectorError(AppModule)[ActivatedRoute -> ActivatedRoute -> ActivatedRoute]:
NullInjectorError: No provider for ActivatedRoute!
at NullInjector.get (http://localhost:4200/vendor.js:16926:27)
at R3Injector.get (http://localhost:4200/vendor.js:30642:33)
at R3Injector.get (http://localhost:4200/vendor.js:30642:33)
at R3Injector.get (http://localhost:4200/vendor.js:30642:33)
at NgModuleRef$1.get (http://localhost:4200/vendor.js:47971:33)
at Object.get (http://localhost:4200/vendor.js:45804:35)
at getOrCreateInjectable (http://localhost:4200/vendor.js:20704:39)
at Module.ɵɵdirectiveInject (http://localhost:4200/vendor.js:34541:12)
at NodeInjectorFactory.BookComponent_Factory [as factory] (http://localhost:4200/main.js:733:153)
at getNodeInjectable (http://localhost:4200/vendor.js:20849:44)
Actually I had this problem since I use providers. Is it hard to understand, because of console doesn't give any class line code. However I'm trying to describe here useful classes that should use it by following, if more classes needs, I will do that:
--app.module.ts--
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BookComponent } from './components/book/book.component';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { BooklistComponent } from './components/booklist/booklist.component';
import { BookEditComponent } from './components/book-edit/book-edit.component';
import { TreeComponent } from './components/tree/tree.component';
import { NgInitDirective } from './directive/ng-init/ng-init.directive';
// for angular firebase #https://github.com/angular/angularfire/blob/master/docs/install-and-setup.md
import { AngularFireModule } from '#angular/fire';
import { AngularFirestore } from '#angular/fire/firestore';
import { environment } from '../environments/environment';
// import our service (that uses firebase)
import { CartService } from './services/cart/cart.service'
import { HttpModule } from '#angular/http';
#NgModule({
declarations: [
AppComponent,
BookComponent,
BooklistComponent,
BookEditComponent,
TreeComponent,
NgInitDirective
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
ReactiveFormsModule,
AngularFireModule.initializeApp(environment.firebase), // have a look in firebase.ts
AngularFireModule,
HttpModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
--app-routing.module.ts--
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { BookComponent } from './components/book/book.component';
import { BookEditComponent } from './components/book-edit/book-edit.component';
import { BooklistComponent } from './components/booklist/booklist.component';
const routes: Routes = [
{ path: 'books/:title', component: BookComponent},
{ path: 'books/:title/edit', component: BookEditComponent},
{ path: 'books', component: BooklistComponent},
{
path: '',
redirectTo: 'books/',
pathMatch: 'full'
}
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
--book.component.ts--
import { Component, OnInit, Input, Output, EventEmitter } from '#angular/core';
import { BookModel } from '../../models/book/book.model';
import { CurrencyPipe } from '#angular/common';
import { ActivatedRoute } from '#Angular/router'
import { CartService } from '../../services/cart/cart.service';
#Component({
selector: 'book',
templateUrl: './book.component.html',
styleUrls: ['./book.component.css']
})
export class BookComponent implements OnInit {
#Input() book: BookModel;
#Output() addToCart: EventEmitter<BookModel> = new EventEmitter();
constructor(private route: ActivatedRoute, private cs: CartService) {
route.params.subscribe(res => {
this.book = BookModel.find(res['title']);
});
}
ngOnInit(): void {
}
sendToCart() {
this.addToCart.emit(this.book);
// the following method is added in cart.service.ts
this.cs.add(this.book);
}
// methods
votesCounter() {
return this.book.upvotes;
}
upvote() {
return this.book.upvotes++;
}
}
As I use app-routing.module.ts, there is a quite difference in app.module of tutorial (that puts also routing stuffs inside it):
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { RouterModule, Routes } from '#angular/router';
import { AngularFireModule } from 'angularfire2';
import { AngularFirestore } from 'angularfire2/firestore';
import { environment } from '../environments/environment';
import { AppComponent } from './app.component';
import { BookComponent } from './components/book/book.component';
import { BookListComponent } from './components/book-list/book-list.component';
import { BookEditComponent } from './components/book-edit/book-edit.component';
import { TreeComponent } from './components/tree/tree.component';
import { NgInitDirective } from './directive/ng-init/ng-init.directive';
import { CartService } from './services/cart/cart.service';
const bookRoutes: Routes = [
{ path: 'books/:title', component: BookComponent },
{ path: 'books/:title/edit', component: BookEditComponent },
{ path: 'books', component: BookListComponent },
{
path: '',
redirectTo: 'books/',
pathMatch: 'full'
}
]
#NgModule({
declarations: [
AppComponent,
BookComponent,
BookListComponent,
BookEditComponent,
TreeComponent,
NgInitDirective
],
imports: [
RouterModule.forRoot(bookRoutes),
BrowserModule,
FormsModule,
ReactiveFormsModule,
AngularFireModule.initializeApp(environment.firebase),
AngularFireModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
I tryed with solutions given from similar questions, but it doesn't work.
You have a typing error,
change #Angular/router with #angular/router in book.component.ts
I'm getting error:
Cannot read property 'path' of undefined
when I go to login page.Login page is separate template from home layout.then I created login.component.ts as <router-outlet> and auth.component.ts for my login page.
But home page working fine. error occur only load separate login page:
This is my folder structure:
login.component.ts:
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor() { }
ngOnInit() { }
}
login.route.ts:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { RouterModule, Routes } from '#angular/router';
import { NoAuthGuard } from '../no-auth-guard.service';
import { AuthComponent } from '../login/auth.component';
export const AUTH_ROUTES: Routes = [
{
path: '', component: AuthComponent,// canActivate: [NoAuthGuard]
},
{
path: 'login', component: AuthComponent,// canActivate: [NoAuthGuard]
},
{
path: 'register', component: AuthComponent,// canActivate: [NoAuthGuard]
}
]
login.route.html:
<router-outlet></router-outlet>
auth.component.ts:
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '#angular/forms';
import { ActivatedRoute, Router } from '#angular/router';
import { Errors, UserService } from '../../shared';
import { UserLogin } from '../../shared/models';
#Component({
selector: 'auth-page',
styleUrls: ['./auth.component.css'],
templateUrl: './auth.component.html'
})
export class AuthComponent implements OnInit {
authLoginForm: FormGroup;
authRegisterForm: FormGroup;
constructor(private route: ActivatedRoute, private router: Router, private userService: UserService, private fb: FormBuilder) {
// use FormBuilder to create a form group
-- some code here
// end use FormBuilder to create a form group
}
ngOnInit() {}
userLogin() { }
userRegister() {}
}
app-routing.module.ts:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { RouterModule, Routes } from '#angular/router';
import { NoAuthGuard } from './auth/no-auth-guard.service';
import { HomeAuthResolver } from './layout/home-auth-resolver.service';
import { LoginComponent, AUTH_ROUTES } from './auth/index';
import {LayoutComponent, PUBLIC_ROUTES } from './layout/index';
const routes: Routes = [
{ path: 'login', component: LoginComponent,data: { title: 'Public Views' }, children: AUTH_ROUTES },
{ path: 'register', component: LoginComponent,data: { title: 'Public Views' }, children: AUTH_ROUTES },
{ path: '', component: LayoutComponent, data: { title: 'Secure Views' }, children: PUBLIC_ROUTES },
{ path: '**', redirectTo: 'home' }
];
#NgModule({
imports: [
CommonModule,
RouterModule.forRoot(routes)
],
exports: [RouterModule]
})
export class AppRoutingModule { }
This problem lies in the ambiguity of your routing scheme. It's also worth noting the Routes is an array and thus ordered. Routes are evaluated in order they are defined in that array.
So move your empty route (path: '') in login.route.ts to the last position in the AUTH_ROUTES array.
I am working on this angular2 project in which I am using ROUTER_DIRECTIVES to navigate from one component to other.
There are 2 components. i.e. PagesComponent & DesignerComponent.
I want to navigate from PagesComponent to DesignerComponent.
So far its routing correctly but I needed to pass page Object so designer can load that page object in itself.
I tried using RouteParams But its getting page object undefined.
below is my code:
pages.component.ts
import {Component, OnInit ,Input} from 'angular2/core';
import { GlobalObjectsService} from './../../shared/services/global/global.objects.service';
import { ROUTER_DIRECTIVES, RouteConfig } from 'angular2/router';
import { DesignerComponent } from './../../designer/designer.component';
import {RouteParams} from 'angular2/router';
#Component({
selector: 'pages',
directives:[ROUTER_DIRECTIVES,],
templateUrl: 'app/project-manager/pages/pages.component.html'
})
#RouteConfig([
{ path: '/',name: 'Designer',component: DesignerComponent }
])
export class PagesComponent implements OnInit {
#Input() pages:any;
public selectedWorkspace:any;
constructor(private globalObjectsService:GlobalObjectsService) {
this.selectedWorkspace=this.globalObjectsService.selectedWorkspace;
}
ngOnInit() { }
}
In the html, I am doing following:
<scrollable height="300" class="list-group" style="overflow-y: auto; width: auto; height: 200px;" *ngFor="#page of pages">
{{page.name}}<a [routerLink]="['Designer',{page: page}]" title="Page Designer"><i class="fa fa-edit"></i></a>
</scrollable>
In the DesignerComponent constructor I have done the following:
constructor(params: RouteParams) {
this.page = params.get('page');
console.log(this.page);//undefined
}
So far its routing correctly to designer, but when I am trying to access page Object in designer then its showing undefined.
Any solutions?
You can't pass objects using router params, only strings because it needs to be reflected in the URL. It would be probably a better approach to use a shared service to pass data around between routed components anyway.
The old router allows to pass data but the new (RC.1) router doesn't yet.
Update
data was re-introduced in RC.4 How do I pass data in Angular 2 components while using Routing?
It changes in angular 2.1.0
In something.module.ts
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { BlogComponent } from './blog.component';
import { AddComponent } from './add/add.component';
import { EditComponent } from './edit/edit.component';
import { RouterModule } from '#angular/router';
import { MaterialModule } from '#angular/material';
import { FormsModule } from '#angular/forms';
const routes = [
{
path: '',
component: BlogComponent
},
{
path: 'add',
component: AddComponent
},
{
path: 'edit/:id',
component: EditComponent,
data: {
type: 'edit'
}
}
];
#NgModule({
imports: [
CommonModule,
RouterModule.forChild(routes),
MaterialModule.forRoot(),
FormsModule
],
declarations: [BlogComponent, EditComponent, AddComponent]
})
export class BlogModule { }
To get the data or params in edit component
import { Component, OnInit } from '#angular/core';
import { Router, ActivatedRoute, Params, Data } from '#angular/router';
#Component({
selector: 'app-edit',
templateUrl: './edit.component.html',
styleUrls: ['./edit.component.css']
})
export class EditComponent implements OnInit {
constructor(
private route: ActivatedRoute,
private router: Router
) { }
ngOnInit() {
this.route.snapshot.params['id'];
this.route.snapshot.data['type'];
}
}
You can do this:
app-routing-modules.ts:
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { PowerBoosterComponent } from './component/power-booster.component';
export const routes: Routes = [
{ path: 'pipeexamples',component: PowerBoosterComponent,
data:{ name:'shubham' } },
];
#NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
In this above route, I want to send data via a pipeexamples path to PowerBoosterComponent.So now I can receive this data in PowerBoosterComponent like this:
power-booster-component.ts
import { Component, OnInit } from '#angular/core';
import { Router, ActivatedRoute, Params, Data } from '#angular/router';
#Component({
selector: 'power-booster',
template: `
<h2>Power Booster</h2>`
})
export class PowerBoosterComponent implements OnInit {
constructor(
private route: ActivatedRoute,
private router: Router
) { }
ngOnInit() {
//this.route.snapshot.data['name']
console.log("Data via params: ",this.route.snapshot.data['name']);
}
}
So you can get the data by this.route.snapshot.data['name'].
1. Set up your routes to accept data
{
path: 'some-route',
loadChildren:
() => import(
'./some-component/some-component.module'
).then(
m => m.SomeComponentModule
),
data: {
key: 'value',
...
},
}
2. Navigate to route:
From HTML:
<a [routerLink]=['/some-component', { key: 'value', ... }> ... </a>
Or from Typescript:
import {Router} from '#angular/router';
...
this.router.navigate(
[
'/some-component',
{
key: 'value',
...
}
]
);
3. Get data from route
import {ActivatedRoute} from '#angular/router';
...
this.value = this.route.snapshot.params['key'];