Error: Template parse errors: There is no directive with "exportAs" set to "bs-tooltip" - angular6

I am pretty new to Karma/jasmine. While writing a test case, i have encountered this error:
Error: Template parse errors: There is no directive with "exportAs" set to "bs-tooltip"
html
<div class="col-md-12 align-center">
<img class="some-class" src="{{ someVariable.imgUrl }}" [tooltip]="someText" triggers="" placement="right"
#pop="bs-tooltip" (click)="someMethod(param1, param2)">
<p class="some-class">{{ someVariable.name }}</p>
</div>
spec file:
import * as fromAuth from './../../../auth/store/auth.reducers';
import { Store, StoreModule } from '#ngrx/store';
import { ComponentFixture, TestBed } from '#angular/core/testing';
import { NO_ERRORS_SCHEMA, CUSTOM_ELEMENTS_SCHEMA } from '#angular/core';
import { MyComponent } from './upcoming-movies.component';
import { HttpClientTestingModule } from '#angular/common/http/testing';
import { RouterTestingModule } from '#angular/router/testing';
import { ModalModule } from 'ngx-bootstrap';
import { SharedModule } from './../../../shared/shared.module';
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
StoreModule.forRoot({
...fromAuth.authReducer
}),
HttpClientTestingModule,
RouterTestingModule,
ModalModule.forRoot(),
SharedModule,
],
declarations: [
MyComponent
],
schemas: [NO_ERRORS_SCHEMA, CUSTOM_ELEMENTS_SCHEMA]
}).compileComponents();
store = TestBed.get(Store);
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
});
it('should be created', () => {
expect(component).toBeTruthy();
});
});
And this is the error which i am facing
Error: Template parse errors:
There is no directive with "exportAs" set to "bs-tooltip" ("some-class" src="{{ someVariable.imgUrl }}" [tooltip]="someText" triggers=""
placement="right" [ERROR ->]#pop="bs-tooltip" (click)="someMethod(param1, param2)">
<p class="dash-slate-text sub-text"): ng:///DynamicTestModule/MyComponent.html#33:134
at syntaxError (http://localhost:9876/_karma_webpack_/webpack:/C:/WorkSpace_2/f360-web/node_modules/#angular/compiler/esm5/compiler.js:485:22)
at TemplateParser.parse (http://localhost:9876/_karma_webpack_/webpack:/C:/WorkSpace_2/f360-web/node_modules/#angular/compiler/esm5/compiler.js:24667:1)
at JitCompiler._parseTemplate (http://localhost:9876/_karma_webpack_/webpack:/C:/WorkSpace_2/f360-web/node_modules/#angular/compiler/esm5/compiler.js:34620:1)
at JitCompiler._compileTemplate (http://localhost:9876/_karma_webpack_/webpack:/C:/WorkSpace_2/f360-web/node_modules/#angular/compiler/esm5/compiler.js:34595:1)
at http://localhost:9876/_karma_webpack_/webpack:/C:/WorkSpace_2/f360-web/node_modules/#angular/compiler/esm5/compiler.js:34496:48
at Set.forEach (<anonymous>)
at JitCompiler._compileComponents (http://localhost:9876/_karma_webpack_/webpack:/C:/WorkSpace_2/f360-web/node_modules/#angular/compiler/esm5/compiler.js:34496:1)
at http://localhost:9876/_karma_webpack_/webpack:/C:/WorkSpace_2/f360-web/node_modules/#angular/compiler/esm5/compiler.js:34384:1
at Object.then (http://localhost:9876/_karma_webpack_/webpack:/C:/WorkSpace_2/f360-web/node_modules/#angular/compiler/esm5/compiler.js:474:33)
at JitCompiler._compileModuleAndAllComponents (http://localhost:9876/_karma_webpack_/webpack:/C:/WorkSpace_2/f360-web/node_modules/#angular/compiler/esm5/compiler.js:34382:1)
Maybe I am missing some bootstrap module in imports. Please help me resolve this matter.

Found the solution. I imported ModalModule
import { ModalModule } from 'ngx-bootstrap';
and inside beforeEach(),
imports: [ModalModule.forRoot()]

This error is because TooltipModule is not imported.
Import the following:
import { TooltipModule } from 'ngx-bootstrap/tooltip';
and inside beforeEach(),
imports: [TooltipModule.forRoot()]

Related

Failed: Unexpected directive 'NewPracticeQuestionComponent' imported by the module 'DynamicTestModule'. Please add a #NgModule annotation

I am unit-testing a commponent which uses two other components. The other components are created when button is clicked
.html
<div id="homepage-top-div" class="homepage-component-css-grid-container"> ...
<button id="get-question-list-button" [routerLink]="questionListRouterLink" class="btn content-div__button--blue css-grid-item-button-div btn-sm">See Questions</button>
</div>
<div id="practice-component-top-div" class="css-grid-container-div common-styles-div--white"> <!-- 4 rows, 1 column-->
...
<button id="new-question-button" [routerLink]="newQuestionRouterLink" class="btn content-div__button--blue css-grid-item-button-div btn-sm">Create a Question</button>
</div>
</div>
.ts
export class HomepageContentComponentComponent implements OnInit {
public questionListRouterLink="/practice-question-list";
public newQuestionRouterLink="/new-practice-question";
constructor() {
}
ngOnInit() {
}
}
I created a spec but I get the following error when I run it - Failed: Unexpected directive 'NewPracticeQuestionComponent' imported by the module 'DynamicTestModule'. Please add a #NgModule annotation.
The spec is
import {async, ComponentFixture, fakeAsync, TestBed, tick} from '#angular/core/testing';
import { HomepageContentComponentComponent } from './homepage-content-component.component';
import {RouterTestingModule} from "#angular/router/testing";
import {AppRoutingModule} from "../app-routing.module";
import {Router} from "#angular/router";
import {routes} from '../app-routing.module';
import {NewPracticeQuestionComponent} from "../new-practice-question/new-practice-question.component";
import {PraticeQuestionListComponent} from "../pratice-question-list/pratice-question-list.component";
import {NgModule} from "#angular/core";
import {AppModule} from "../app.module";
fdescribe('HomepageContentComponentComponent', () => {
let component: HomepageContentComponentComponent;
let fixture: ComponentFixture<HomepageContentComponentComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports:[
AppModule,
AppRoutingModule,
RouterTestingModule.withRoutes(routes),
NewPracticeQuestionComponent,
PraticeQuestionListComponent
],
declarations: [ HomepageContentComponentComponent,
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(HomepageContentComponentComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should navigate to New Questions Component when New Question button is clicked',fakeAsync(()=>{
let router:Router;
let location:Location;
router = TestBed.get(Router);
location = TestBed.get(Location);
console.log('initial router is ',router);
console.log('initial location is ',location);
router.initialNavigation();
router.navigate(['new-practice-question']);
tick();
console.log('new router is ',router);
console.log('new location is ',location);
expect(location.pathname).toBe('/new-practice-question');
}));
});
the issue was that NewQuestionComponent and PracticeListComponent should have been in declarations, not imports

NullInjectorError: No provider for JwtHelperService

I'm in Angular 5.
First: npm install #auth0/angular-jwt --save
Then I import it: import { JwtHelperService } from '#auth0/angular-jwt';
This is my authentication service:
import { JwtHelperService } from '#auth0/angular-jwt';
#Injectable()
export class AuthService {
constructor(public jwtHelper: JwtHelperService) { }
public isAuthenticated(): boolean {
console.log (localStorage['token']);
const token = localStorage.getItem('token');
// Check wheter the token is expired and return true or false
return !this.jwtHelper.isTokenExpired(token);
}
}
And this is my Guard service
export class GuardService implements CanActivate {
constructor(public auth: AuthService, public router: Router) {}
canActivate(): boolean {
if (!this.auth.isAuthenticated()){
console.log ('bye');
this.router.navigate(['/login']);
return false;
}
console.log ('Welcome');
return true;
}
}
There is a token in the localstorage:
eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImFjMTUyNzZhZjA2MjU1YTdlMDM0MmQ5ODg4N2M1ZmI2ZWNmM2RlNGUyNjhmYTc4MTliODRhOTVmMmJiNGZiMTliMDFkNjBhNWRlNjhlN2VlIn0.eyJhdWQiOiJmMDExY2M1OC00MGNlLTQzYTktOGY3MS04NDI0OTRlM2E5OTciLCJqdGkiOiJhYzE1Mjc2YWYwNjI1NWE3ZTAzNDJkOTg4ODdjNWZiNmVjZjNkZTRlMjY4ZmE3ODE5Yjg0YTk1ZjJiYjRmYjE5YjAxZDYwYTVkZTY4ZTdlZSIsImlhdCI6MTUyMzI5NzkzNSwibmJmIjoxNTIzMjk3OTM1LCJleHAiOjE1MjMyOTgyMzUsInN1YiI6IjIiLCJzY29wZXMiOlsiYXV0aGVudGljYXRlZCIsImFuZ3VkcnUiXX0.RNY2Yb9xiJDcER4rtHEAYMmoLyvPYij-upZc97q-mSgICKE6_xWih_IBjY4cHQXkkiRyCXaqCfwfMM4YWVjv7bsMlLN5bWlH0JTeYoYf2gENLBIG51NwGpU3iAl8KG_51ljZKbs3RE_ULDbphM1NG8BhobVQ5RlObWzejrkPcMHqlGJaMOMLQuXC1iBR2jI9tlfiP4RD4FUUsRkUEUJ5PSIRl34jWoTv31SSf1bkv43q3YeKTfk6pXZ5Ft_eV8G871KkmQSHANAn26A5ujj2FOh-uCV_VNJ97RuTQ6J4NP2YB-mMaWYpZ1xF-4ndqafRGFXJ_8euBO4cA36zvP3B7g
And this is the error:
ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[AuthService -> JwtHelperService]:
StaticInjectorError(Platform: core)[AuthService -> JwtHelperService]:
NullInjectorError: No provider for JwtHelperService!
Error: StaticInjectorError(AppModule)[AuthService -> JwtHelperService]:
StaticInjectorError(Platform: core)[AuthService -> JwtHelperService]:
NullInjectorError: No provider for JwtHelperService!
at _NullInjector.get (core.js:1002)
at resolveToken (core.js:1300)
at tryResolveToken (core.js:1242)
at StaticInjector.get (core.js:1110)
at resolveToken (core.js:1300)
at tryResolveToken (core.js:1242)
at StaticInjector.get (core.js:1110)
at resolveNgModuleDep (core.js:10854)
at _createClass (core.js:10891)
at _createProviderInstance$1 (core.js:10865)
at _NullInjector.get (core.js:1002)
at resolveToken (core.js:1300)
at tryResolveToken (core.js:1242)
at StaticInjector.get (core.js:1110)
at resolveToken (core.js:1300)
at tryResolveToken (core.js:1242)
at StaticInjector.get (core.js:1110)
at resolveNgModuleDep (core.js:10854)
at _createClass (core.js:10891)
at _createProviderInstance$1 (core.js:10865)
at resolvePromise (zone.js:814)
at resolvePromise (zone.js:771)
at eval (zone.js:873)
at ZoneDelegate.invokeTask (zone.js:421)
at Object.onInvokeTask (core.js:4740)
at ZoneDelegate.invokeTask (zone.js:420)
at Zone.runTask (zone.js:188)
at drainMicroTaskQueue (zone.js:595)
Also, it shows me the route, but without the array from the service...
A little late to the party, but I ran into the same issue trying to follow the standalone docs and what it doesn't cover is the need to import the options InjectionToken which is referenced in the constructor of the service:
import { JwtHelperService, JWT_OPTIONS } from '#auth0/angular-jwt';
...
providers: [
{ provide: JWT_OPTIONS, useValue: JWT_OPTIONS },
JwtHelperService
]
You need to use JwtModule provided by the #auth0/angular-jwt, which will add JwtHelperService to the providers, or you need to add it manually to the modules provider.
Something like
const JWT_Module_Options: JwtModuleOptions = {
config: {
tokenGetter: yourTokenGetter,
whitelistedDomains: yourWhitelistedDomains
}
};
#NgModule({
imports: [
JwtModule.forRoot(JWT_Module_Options)
],
...
Fore more see Documentation
This problem occurs because you have not added JWTmodule to imports in app.module.ts
export function tokenGetter() {
return localStorage.getItem("access_token");
}
JwtModule.forRoot({
config: {
tokenGetter: tokenGetter,
allowedDomains: ["example.com"],
disallowedRoutes: ["http://example.com/examplebadroute/"],
},
}),
For future reference, if all you want to use JwtHelper for is decoding, like in this case checking if the token is expired, then you can use this.
import { JwtHelperService } from '#auth0/angular-jwt';
const jwtHelper = new JwtHelperService();
#Injectable()
export class AuthService {
public isAuthenticated(): boolean {
const token = localStorage.getItem('token');
// Check if the token is expired and return true or false
return !this.jwtHelper.isTokenExpired(token);
}
Source: Documentation
I battled with this issue as well. I found a workaround:
Test configuration
In your modulename.spec.ts make sure that you configure a provider for the JwtHelperService (In my case it was AuthGuard.spec.ts):
import { TestBed, inject, waitForAsync } from '#angular/core/testing';
import { RouterTestingModule } from "#angular/router/testing";
import { HttpTestingController, HttpClientTestingModule } from '#angular/common/http/testing';
import { JwtModule, JwtHelperService } from '#auth0/angular-jwt';
import { AuthGuard } from './auth.guard';
let jwtHelper: JwtHelperService;
const testBedConfiguration = {
imports: [
RouterTestingModule.withRoutes([]),
HttpClientTestingModule,
JwtModule.forRoot({ // for JwtHelperService
config: {
tokenGetter: () => {
return '';
}
}
})
],
providers: [
AuthGuard,
JwtHelperService
]
}
describe('AuthGuard', () => {
beforeEach(() => {
TestBed.configureTestingModule(testBedConfiguration);
jwtHelper = TestBed.get(JwtHelperService);
});
it('should ...', inject([AuthGuard], (guard: AuthGuard) => {
expect(guard).toBeTruthy();
}));
});
This solved my issue, but since my implementation was in my auth service which is used by my authguard for the routes, I have to include that config in every single page I have protected by the authguard.
The simplest solution which worked for me is declaring constant variable type of "JwtHelperService" instead of declaring it in a constructor.
const helper = new JwtHelperService ();
Now use helper services with helper constant
return !helper.isTokenExpired(token);
If you used #auth0/angular-jwt to get the jwt assistance and used dependency injection to access the module it is necessary to import jwt module to the app.module.ts or what ever the module you used.moreover you have more privileges to configure your module importers with disallowed domains, allowed domains , header name, custom factory functions etc.
import { JwtModule } from "#auth0/angular-jwt";
import { HttpClientModule } from "#angular/common/http";
export function tokenGetter() {
return localStorage.getItem("access_token");
}
#NgModule({
bootstrap: [AppComponent],
imports: [
// ...
HttpClientModule,
JwtModule.forRoot({
config: {
tokenGetter: tokenGetter,
allowedDomains: ["localhost:3001", "foo.com", "bar.com"]
},
}),
],
})
export class AppModule {}
if you don't want to inject it, you can instantiate.
import { JwtHelperService } from "#auth0/angular-jwt";
const helper = new JwtHelperService();
const decodedToken = helper.decodeToken(myRawToken);
const expirationDate = helper.getTokenExpirationDate(myRawToken);
const isExpired = helper.isTokenExpired(myRawToken);
import { JwtModule, JwtHelperService } from '#auth0/angular-jwt';
public jwtHelper: JwtHelperService = new JwtHelperService();
constructor(
private http: Http,
) { }
decodeToken() {
const token = localStorage.getItem('token');
return this.jwtHelper.decodeToken(token);
}
this fixed my problem
https://github.com/auth0/angular2-jwt/issues/482#issuecomment-569251938
I fixed this issues by changing my import from :
import { JwtHelperService } from '#auth0/angular-jwt';
to
import { JwtHelperService } from '#auth0/angular-jwt/src/jwthelper.service';

Angular2 won't load json file. Error: Can't resolve all parameters for AppComponent

I am trying to load a json file into my Angular app, but can't find the culprit. It keeps telling me it can't resolve all parameters of my component.
(loading the data directly from the component worked, so it has to do with the code I added most recently for loading data from a json file)
My module:
import { NgModule} from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { HttpModule } from '#angular/http';
import { Injectable } from '#angular/core';
import { Http, Response } from '#angular/http';
import 'rxjs/Rx';
import {Observable} from 'rxjs/Observable';
import { AppComponent } from './component.app';
#Injectable()
export class Service {
constructor(private _http: Http) {}
getData(){
return this.http.get('./assets/data/data.json')
.map(res => res.json())
}
}
#NgModule({
imports: [
BrowserModule,
HttpModule
],
declarations: [
AppComponent
],
bootstrap: [
AppComponent
],
providers: [
Service
]
})
export class AppModule {}
My component:
import { Component } from '#angular/core';
#Component({
selector: 'app',
templateUrl: './assets/partials/component-app.html',
styleUrls: ['./assets/css/component-app.css']
})
export class AppComponent {
tests: any;
constructor(private service : Service){}
ngOnInit() {
this.service.getData()
.subscribe(data => {
this.tests = data;
})
}
The error:
(index):18 Error: Error: Can't resolve all parameters for AppComponent: (?).
at CompileMetadataResolver.getDependenciesMetadata (http://localhost:3000/node_modules/#angular/compiler//bundles/compiler.umd.js:14404:21)
at CompileMetadataResolver.getTypeMetadata (http://localhost:3000/node_modules/#angular/compiler//bundles/compiler.umd.js:14301:28)
at CompileMetadataResolver.getDirectiveMetadata (http://localhost:3000/node_modules/#angular/compiler//bundles/compiler.umd.js:14074:30)
at eval (http://localhost:3000/node_modules/#angular/compiler//bundles/compiler.umd.js:14167:51)
at Array.forEach (<anonymous>)
at CompileMetadataResolver.getNgModuleMetadata (http://localhost:3000/node_modules/#angular/compiler//bundles/compiler.umd.js:14161:51)
at RuntimeCompiler._compileComponents (http://localhost:3000/node_modules/#angular/compiler//bundles/compiler.umd.js:16803:49)
at RuntimeCompiler._compileModuleAndComponents (http://localhost:3000/node_modules/#angular/compiler//bundles/compiler.umd.js:16741:39)
at RuntimeCompiler.compileModuleAsync (http://localhost:3000/node_modules/#angular/compiler//bundles/compiler.umd.js:16732:23)
at PlatformRef_._bootstrapModuleWithZone (http://localhost:3000/node_modules/#angular/core//bundles/core.umd.js:6954:29)
data.json, I need to loop through test_cases and Test_steps:
{
"test_run_id": "A233-CA92-3293-B9AA",
"app_name": "Chewy.com",
"time_stamp": "2018-01-20T12:00:00Z",
"test_cases": [
{
"test_name": "View dog bone",
"status": true,
"test_steps": [
{
"step_name": "Click Dog Category",
"screenshot": "file1.png",
"launch_times": [
100,
134,
123
],
HTML:
<section class="tested-app" *ngFor = "let item of tests">
<h2>----<span> {{ item.app_name }} </span>----</h2>
<p id="time"> Time: <span> {{item.time_stamp}} </span> </p>
<section class="flexWrap">
<div class="module" *ngFor="let subItem of item.test_cases">
<h3> {{ subItem.test_name }} </h3>
<p class="status"> {{subItem.status}} </p>
<div class="step" *ngFor = "let testStep of subItem.test_steps">
<h4>{{testStep.step_name}}</h4>
<img src="../assets/images/{{testStep.screenshot}}">
You need to import your service in app.component.ts
import { Service} from '...';
you also need implement OnInit
export class AppComponent implements OnInit
In your getData function, you have typo:
return this._http.get('./assets/data/data.json')
And the most important is you need put your service out of app.module.ts Why? Because it will create a circular dependency:
app.module.ts -> app.component.ts -> app.module.ts
Create a new service.ts
import { Injectable } from '#angular/core';
import { Http, Response } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class Service {
constructor(private _http: Http) {}
getData(){
return this._http.get('./assets/data/data.json')
.map(res => res.json());
}
}
Import it in app.module
import { Service } from './service';
Just like the first line:
import { Component } from '#angular/core';,
you need to add a line
import { Service } from X
where X is the path of the file which defines Service. I guess in your case you are defining Service in app.module, so try
import { Service } from ./app.module.ts
(if app.module.ts is in same directory, otherwise include path to that directory)

How to Access JSON Object Properties as table in Angular 2

I am new in Angular 2 and trying to access data from API. As Output, I am getting API response on my browser as all JSON objects. But I don't know how to access the individual properties. below is my code:
test.component.ts
import { Component, OnInit } from '#angular/core';
import { HttpTestService } from './http-test.service';
#Component({
selector: 'http-test',
templateUrl: './http-test.component.html',
providers: [HttpTestService]
})
export class HttpTestComponent implements OnInit {
getData:string;
postData: string;
constructor(private _httpService: HttpTestService) { }
getTest(){
this._httpService.getData()
.subscribe(
data => this.getData = JSON.stringify(data)
);
}
ngOnInit() {
}
}
test.service.ts
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class HttpTestService {
constructor(private _http: Http) { }
getData(){
return this._http.get("http://jsonplaceholder.typicode.com/users")
.map(res => res.json())
}
}
test.component.html
In this file, when I use {{getdata}} I get whole JSON object, but when I try to access any of its property I get ERROR
<button (click)="getTest()">Get Result</button>
output:
<ul>
<li>{{ getData[0][time] }}</li>
</ul>
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { AppComponent } from './app.component';
import { HttpTestComponent } from './http-test/http-test.component';
#NgModule({
declarations: [
AppComponent,
HttpTestComponent,
],
imports: [
BrowserModule,
FormsModule,
HttpModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
**Output: **
this.getData = JSON.stringify(data) will make your object a string and you can't reach a strings fields like an object. Remove it.
Then you need to reach to time key as a "string"
Try:
<li>{{ getData[0]['time'] }}</li>
or
<li>{{ getData[0]?.time }}</li>
Example: http://plnkr.co/edit/CB3oGppm4fvoEExfDSRc?p=preview
Change Your code in plunker as shown below :
import { Component } from '#angular/core';
import { ConfigurationService } from './ConfigurationService';
#Component({
selector: 'my-app',
template: `
<table>
<tr *ngFor="let data of getData">
<td>{{data.address.street}}</td>
<td>{{data.address.geo.lat}}</td>
<td>{{data.name}}</td>
<td>{{data.email}}</td>
</tr>
</table>
`
})
export class AppComponent {
getData : any[] ;
constructor(private _ConfigurationService: ConfigurationService)
{
console.log("Reading _ConfigurationService ");
//console.log(_ConfigurationService.getConfiguration());
this._ConfigurationService.getConfiguration()
.subscribe(
(data)=> {
this.getData = data;
console.log(this.getData);
},
(error) => console.log("error : " + error)
);
}
}

Ng2-table not working with latest Angular2 version

I am currently using Angular2 for my application and now I want to add ng2-table to my component.
ng2-Table on Git
I am getting this error and couldn't help but ask:
angular2-polyfills.js:487 Unhandled Promise rejection: Template parse errors:
Can't bind to 'colums' since it isn't a known property of 'ng-table'.
1. If 'ng-table' is an Angular component and it has 'colums' input, then
verify that it is part of this module.
2. If 'ng-table' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA"
to the '#NgModule.schema' of this component to suppress this message.
("
</div>-->
<ng-table [ERROR ->][colums]="columns" [rows]="rows" > </ng-table>
<div class="">
"): DeviceOverviewComponent#18:10 ;
Zone: <root> ; Task: Promise.then ; Value: Error: Template parse errors:(…)
In my html I got this:
<ng-table [columns]="columns" [rows]="rows" > </ng-table>
My Component is this:
import { Component } from '#angular/core';
import { Router } from '#angular/router';
import { DeviceService } from '../services/device.service';
#Component({
selector: 'device-overview',
templateUrl: 'dist/html/deviceoverview.component.html',
providers: [DeviceService],
})
export class DeviceOverviewComponent {
devices: any;
columns: any;
rows: any;
constructor(private deviceService: DeviceService, private router: Router) {
}
loadDevices() {
this.deviceService.getDevices()
.then((data) => {
this.devices = data
this.rows = this.devices
})
}
goToDevice(deviceName: string) {
this.router.navigateByUrl('/devices/' + deviceName)
}
ngOnInit() {
this.columns = [
{ title: "test", name: "id" }]
this.loadDevices();
}
}
And my app.module is this:
import { NgModule } from '#angular/core';
import { LocationStrategy, HashLocationStrategy } from '#angular/common';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { Ng2TableModule } from 'ng2-table/ng2-table';
import { AppComponent } from './components/app.component';
import { DeviceOverviewComponent } from './components/deviceoverview.component'
import { DeviceService } from './services/device.service';
import { routing } from './app.routing';
#NgModule({
imports: [
Ng2TableModule,
BrowserModule,
FormsModule,
HttpModule,
routing,
],
declarations: [
DeviceOverviewComponent,
AppComponent,
],
providers:
[
{provide: LocationStrategy, useClass: HashLocationStrategy},
DeviceService,
],
bootstrap: [AppComponent]
})
export class AppModule { }
Does anybody know anything about the Usage of ng2-table? Or is there a valid alternative, since the demo page/usage documentation is not available by now?
I found some alternatives, but lots of them had their last commit a long time ago, which might be a problem, since I am always using latest Angular2.
Thanks for reading and any hel is appreciated!
EDIT:
I've made it to the next step!
I needed to add
import {CUSTOM_ELEMENTS_SCHEMA} from '#angular/core'
#NgModule({ ...,
schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
within my app.module.ts
Now I am getting the table header with the "test" column and the ID property of my row data is displayed correctly.
Even the demo from ng2-table didn't have that import.
I guess docs and demos arent made for newbes nowadays. :/
i see a typo in your html:
[colums]="columns"
It should be
[columns]="columns"
You're missing n
Plunker Example (I also tried it on local machine and it works)
You shouldn't use CUSTOM_ELEMENTS_SCHEMA
systemjs.config.js
map: {
...
'ng2-table': 'npm:ng2-table'
},
packages: {
...
'ng2-table': {
defaultExtension: 'js'
}
}
After long time I close this issue.
In my case I have these structure:
src
--app
-- app.module
-- TravelPlan
-- travel-plan.module
-- test.component
So, I was trying put the ng2-smart-table in app.module, but I was wrong. The correct is put in travel-plan.module.