Am I missing something in the configuration?
ng Version command
Versions
Angular CLI: 1.7.0
Node: 8.1.1
OS: win32 x64
Angular: 5.2.5
... common, compiler, compiler-cli, core, forms, http
... language-service, platform-browser, platform-browser-dynamic
... router
#angular/animations: 5.2.9
#angular/cdk: 5.2.4
#angular/cli: 1.7.0
#angular/material: 5.2.4
#angular-devkit/build-optimizer: 0.3.1
#angular-devkit/core: 0.3.1
#angular-devkit/schematics: 0.3.1
#ngtools/json-schema: 1.2.0
#ngtools/webpack: 1.10.0
#schematics/angular: 0.3.1
#schematics/package-update: 0.3.1
typescript: 2.5.3
webpack-bundle-analyzer: 2.11.1
webpack: 3.11.0
Repro steps
Step 1 Create new project ng new any-name
Step 2 By following steps on https://material.angular.io/guide/getting-started
i.e
npm install --save #angular/material #angular/cdk
npm install --save #angular/animations
Step 3
Material.module.ts
import {MatButtonModule,
MatCheckboxModule} from '#angular/material';
#NgModule({
imports: [MatButtonModule, MatCheckboxModule],
})
export class MaterialModule { }
app.component.html
<div>
<input type="button" mat-button placeholder="Holla!">
<button mat-raised-button >Click me!</button>
<mat-checkbox>Check me!</mat-checkbox>
</div>
App.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import {BrowserAnimationsModule} from '#angular/platform-browser/animations';
import { AppComponent } from './app.component';
import {MaterialModule} from '../shared/material.module'
#NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
MaterialModule,
BrowserAnimationsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
styles.css
/* You can add global styles to this file, and also import other style files */
#import "~#angular/material/prebuilt-themes/indigo-pink.css";
Observed behavior
compiler.js:485 Uncaught Error: Template parse errors:
'mat-checkbox' is not a known element:
If 'mat-checkbox' is an Angular component, then verify that it is part of this module.
If 'mat-checkbox' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '#NgModule.schemas' of this component to suppress this message. ("
Click me!
[ERROR ->]Check me!
"): ng:///AppModule/AppComponent.html#4:2
at syntaxError (compiler.js:485)
at TemplateParser.parse (compiler.js:24668)
at JitCompiler._parseTemplate (compiler.js:34621)
at JitCompiler._compileTemplate (compiler.js:34596)
at eval (compiler.js:34497)
at Set.forEach ()
at JitCompiler._compileComponents (compiler.js:34497)
at eval (compiler.js:34367)
at Object.then (compiler.js:474)
at JitCompiler._compileModuleAndComponents (compiler.js:34366)
syntaxError # compiler.js:485
TemplateParser.parse # compiler.js:24668
JitCompiler._parseTemplate # compiler.js:34621
JitCompiler._compileTemplate # compiler.js:34596
(anonymous) # compiler.js:34497
JitCompiler._compileComponents # compiler.js:34497
(anonymous) # compiler.js:34367
then # compiler.js:474
JitCompiler._compileModuleAndComponents # compiler.js:34366
JitCompiler.compileModuleAsync # compiler.js:34260
CompilerImpl.compileModuleAsync # platform-browser-dynamic.js:239
PlatformRef.bootstrapModule # core.js:5567
(anonymous) # main.ts:11
./src/main.ts # main.bundle.js:59
__webpack_require__ # inline.bundle.js:55
0 # main.bundle.js:75
__webpack_require__ # inline.bundle.js:55
webpackJsonpCallback # inline.bundle.js:26
(anonymous) # main.bundle.js:1
Desired behavior
What would like to see implemented?
It should load the angular material components.
Package.json
{
"name": "mat-learn",
"version": "0.0.0",
"license": "MIT",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build --prod",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"#angular/animations": "^5.2.9",
"#angular/cdk": "^5.2.4",
"#angular/common": "^5.2.0",
"#angular/compiler": "^5.2.0",
"#angular/core": "^5.2.0",
"#angular/forms": "^5.2.0",
"#angular/http": "^5.2.0",
"#angular/material": "^5.2.4",
"#angular/platform-browser": "^5.2.0",
"#angular/platform-browser-dynamic": "^5.2.0",
"#angular/router": "^5.2.0",
"core-js": "^2.4.1",
"hammerjs": "^2.0.8",
"rxjs": "^5.5.6",
"zone.js": "^0.8.19"
},
"devDependencies": {
"#angular/cli": "~1.7.0",
"#angular/compiler-cli": "^5.2.0",
"#angular/language-service": "^5.2.0",
"#types/jasmine": "~2.8.3",
"#types/jasminewd2": "~2.0.2",
"#types/node": "~6.0.60",
"codelyzer": "^4.0.1",
"jasmine-core": "~2.8.0",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~2.0.0",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "^1.2.1",
"karma-jasmine": "~1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~5.1.2",
"ts-node": "~4.1.0",
"tslint": "~5.9.1",
"typescript": "~2.5.3"
}
}
Main.ts
import { enableProdMode } from '#angular/core';
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import 'hammerjs';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.log(err));
#import "~#angular/material/prebuilt-themes/indigo-pink.css";
add this in style.css
As per the example given here, you also need to export the material modules from your shared material module
https://material.angular.io/guide/getting-started#step-3-import-the-component-modules
import {MatButtonModule,
MatCheckboxModule} from '#angular/material';
#NgModule({
imports: [MatButtonModule, MatCheckboxModule],
exports: [MatButtonModule, MatCheckboxModule]
})
export class MaterialModule { }
This might be what you was looking for, you need to add few lines to styles in angular.json
"./node_modules/#angular/material/prebuilt-themes/pink-bluegrey.css"
This worked for me. Give a Try!
I was looking for something for a while. But I had just one typo in an import making the whole "Module import" clause fail.
My import was:
import { PopoverModule } from '_components/material/popover';
Instead of:
import { PopoverModule } from './_components/material/popover';
And it triggered 15+ unrelated errors about material ui components.
Related
The application was built on Angular v4 and was gradually updated with every release up until now. Currently we're on Angular v7 and finally the CEO has agreed to write unit test while it wasn't the case before.
I just created a simple spec to just get started with the tests and start implementing it throughout the project but got stuck for two days with the following error:
AsyncTestZoneSpec is needed for the async() test helper but could not be >found. Please make sure that your environment includes zone.js/dist/async->test.js
While googling for the above error, I found some answers but that was related to Wallaybyjs but rather specific to Angular.
I've tried to reproduce the issue with the brand new installation of the angular project but couldn't really. This might be issue with some dependencies required to be missing to run tests on Angular 7.
Following is the test.ts file:
// This file is required by karma.conf.js and loads recursively all the .spec and framework files
import 'zone.js/dist/long-stack-trace-zone';
import 'zone.js/dist/proxy.js';
import 'zone.js/dist/sync-test';
import 'zone.js/dist/jasmine-patch';
import 'zone.js/dist/async-test';
import 'zone.js/dist/fake-async-test';
import { getTestBed } from '#angular/core/testing';
import {
BrowserDynamicTestingModule,
platformBrowserDynamicTesting
} from '#angular/platform-browser-dynamic/testing';
// Unfortunately there's no typing for the `__karma__` variable. Just declare it as any.
declare const __karma__: any;
declare const require: any;
// Prevent Karma from running prematurely.
__karma__.loaded = function () {};
// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting()
);
// Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context);
// Finally, start Karma to run the tests.
__karma__.start();
and Package.json:
{
"name": "frontend",
"version": "0.1.2-7",
"appVersion": "2.104",
"license": "MIT",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e",
"build-staging": "bash build-staging.sh",
"build-production": "bash build-production.sh",
"compodoc": "npx compodoc -p src/tsconfig.app.json"
},
"private": true,
"dependencies": {
"#angular-devkit/build-angular": "^0.13.9",
"#angular/animations": "7.0.3",
"#angular/common": "7.0.3",
"#angular/compiler": "7.0.3",
"#angular/core": "7.0.3",
"#angular/forms": "7.0.3",
"#angular/http": "7.0.3",
"#angular/platform-browser": "7.0.3",
"#angular/platform-browser-dynamic": "7.0.3",
"#angular/router": "7.0.3",
"#fortawesome/fontawesome-free": "^5.9.0",
"#mobiscroll/angular": "^4.7.3",
"#ng-bootstrap/ng-bootstrap": "^4.2.1",
"#ngx-translate/core": "^11.0.1",
"#ngx-translate/http-loader": "^4.0.0",
"angular2-virtual-scroll": "^0.4.16",
"core-js": "^2.6.9",
"moment": "^2.22.2",
"ng-block-ui": "^2.1.5",
"ng2-charts": "^1.6.0",
"ngx-infinite-scroll": "^7.2.0",
"ngx-lazy-load-images": "^1.3.1",
"rxjs": "^6.5.2",
"rxjs-compat": "^6.5.2",
"zone.js": "^0.8.29"
},
"devDependencies": {
"#angular/cli": "7.0.5",
"#angular/compiler-cli": "^7.2.15",
"#angular/language-service": "7.0.3",
"#compodoc/compodoc": "^1.1.9",
"#types/jasmine": "^2.8.16",
"#types/jasminewd2": "~2.0.2",
"#types/node": "^10.14.10",
"codelyzer": "^4.4.2",
"jasmine-core": "~3.3.0",
"jasmine-spec-reporter": "~4.1.0",
"karma": "^4.1.0",
"karma-chrome-launcher": "~2.1.1",
"karma-cli": "~1.0.1",
"karma-coverage-istanbul-reporter": "^2.0.5",
"karma-jasmine": "~1.1.0",
"karma-jasmine-html-reporter": "^1.4.2",
"protractor": "^5.4.2",
"ts-node": "~7.0.1",
"tslint": "~5.7.0",
"typescript": "3.1.6"
}
}
Following is the component spec:
import { async, ComponentFixture, TestBed } from '#angular/core/testing';
import { InsuranceComponent } from './insurance.component';
import { CartModule } from '../../cart/cart.module';
import { SharedModule } from '../../shared/shared.module';
import { CommonModule } from '#angular/common';
import { MbscModule } from '#mobiscroll/angular';
import { FormsModule } from '#angular/forms';
import { NgbModule } from '#ng-bootstrap/ng-bootstrap';
import { PipeModule } from '../../pipe/pipe.module';
import { InfiniteScrollModule } from 'ngx-infinite-scroll';
import { InsuranceRoutingModule } from '../insurance-routing/insurance-routing.module';
import { InsuranceSearchItemComponent } from '../insurance-search-item/insurance-search-item.component';
// tslint:disable-next-line:max-line-length
import { InsuranceSearchItemDetailsComponent } from '../insurance-search-item/insurance-search-item-details/insurance-search-item-details.component';
describe('Insurance Component', () => {
let component: InsuranceComponent;
let fixture: ComponentFixture<InsuranceComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
CartModule,
SharedModule,
CommonModule,
MbscModule,
FormsModule,
NgbModule,
PipeModule,
InfiniteScrollModule,
InsuranceRoutingModule
],
declarations: [InsuranceComponent, InsuranceSearchItemComponent, InsuranceSearchItemDetailsComponent]
}).compileComponents();
fixture = TestBed.createComponent(InsuranceComponent);
component = fixture.componentInstance;
fixture.detectChanges();
}));
it('should create', () => {
expect(component).toBeTruthy();
});
});
Any help would be appreciated alot.
Thanks
I was getting this error after Angular 11 upgrade.
This line must be the first line in test.ts, before all other imports:
import 'zone.js/dist/zone-testing'; // zone-testing needs to be first import!
The following command was likely deprecated:
ng test --main somecomponent.spec.ts
Instead, use:
ng test
To just run a specific spec instead of all, prefix your describe and it block with f:
fdescribe('whatever', () => {})
I use this command in order to test one file only:
ng test --include somecomponent.spec.ts
You are going to have issues with the --main option as #clean-code has stated.
I had the same problem with with the spectator testing framework.
The solution was, to import jest-preset-angular before the spectator imports.
wrong:
import { defineGlobalsInjections } from '#ngneat/spectator';
import 'jest-preset-angular';
correct:
import 'jest-preset-angular';
import { defineGlobalsInjections } from '#ngneat/spectator';
I had similar issue but with jest testing framework.
After you removed all the karma and jasmine related stuff and installed jest related staff you could have a similar error
zone-testing.js is needed for the async() test helper but could not be found.
Please make sure that your environment includes zone.js/dist/zone-testing.js
And here it is my setup-jest.ts file
import 'jest-preset-angular';
import 'jest-extended';
When I changed one of the imports in the file setup-jest.ts to this
import 'jest-preset-angular/setup-jest';
import 'jest-extended';
Everything works fine now.
To use async() functionality, you need to import zone-testing.
Try importing zone-testing package into your test.ts file.
import 'zone.js/dist/zone-testing'
Refer this link - Angular Documentation
Angular migration from 2.3.0 to 4.3.0 by using the Migration guide from https://update.angular.io.
Already fixed most of the packages version errors, changing packages...
I had updated my packages.json as described below, The log given by the failure, Without AOT :
ERROR in Error: Error encountered resolving symbol values statically.
Function calls are not supported. Consider replacing the function or
lambda with a reference to an exported function (position 55:26 in the
original .ts file), resolving symbol mapValuesToArray in
C:/Users/project/src/app/app.module.ts, resolving
symbol Artefacts in
C:/Users/project/src/app/app.module.ts, resolving symbol AppModule in
C:/Users/project/src/app/app.module.ts, resolving symbol AppModule in
C:/Users/project/selv2/src/app/app.module.ts
This is my app.module.ts file
import {BrowserModule, Title} from '#angular/platform-browser';
import {NgModule} from '#angular/core';
import {FormsModule, ReactiveFormsModule} from '#angular/forms';
import {RouterModule} from '#angular/router';
import {Http, HttpModule} from '#angular/http';
import {TranslateLoader, TranslateModule, TranslateStaticLoader} from
'ng2-translate';
import {DragulaModule} from 'ng2-dragula/ng2-dragula';
import {ImageCropperComponent} from 'ng2-img-cropper';
import {DynamicFormModule} from './shared/dform/dform.module';
import {SpinnerComponent} from '#app/components';
import {MyDatePickerModule} from 'mydatepicker';
import {UuidModule} from 'ng2-uuid';
import {ResponsiveModule} from 'ng2-responsive';
import {Angulartics2GoogleAnalytics, Angulartics2Module} from
'angulartics2';
import {Ng2DeviceDetectorModule} from 'ng2-device-detector';
import {StoreModule} from '#ngrx/store';
import {StoreDevtoolsModule} from '#ngrx/store-devtools';
import {EffectsModule} from '#ngrx/effects';
// Root Application Component
import {AppComponent} from './app.component';
import {PopupModule} from 'ng2-opd-popup';
// Services
import * as services from './services';
import * as guards from './guards';
// Components included using barrel
import * as components from './components';
// Effects
import * as fromEffects from './effects';
// reducers
import {reducer} from './reducers';
import {WindowRefService} from '#app/services';
import {environment} from '../environments/environment';
import {SharedModule} from "#app/shared/shared.module";
import {NotificationsService} from "angular2-
notifications/src/notifications.service";
import {AppRoutingModule} from "#app/app-routing.module";
import {AboutComponent} from "#app/components/about/about.component";
// Elements loading function
/*const mapValuesToArray = (obj) => Object.keys(obj).map(key =>
obj[key]);*/
export function mapValuesToArray (obj){
return [
Object.keys(obj).map(key => obj[key])
];
};
export const apiUrl = (windowRef: WindowRefService) => {
return environment.api_url || windowRef.nativeWindow['__env']['backend']
+ '/api';
};
export const Providers = [
...mapValuesToArray(services),
...mapValuesToArray(guards),
{ provide: 'api_url', useFactory: apiUrl, deps: [WindowRefService] }
];
export const Artefacts = [
...mapValuesToArray(components),
ImageCropperComponent
];
export const Features = [];
export function createTranslateLoader(http: Http) {
return new TranslateStaticLoader(http, './assets/i18n', '.json');
}
#NgModule({
declarations: [
AppComponent,
Artefacts,
Features,
SpinnerComponent,
AboutComponent
],
exports:[RouterModule],
imports: [
SharedModule,
Ng2DeviceDetectorModule.forRoot(),
PopupModule.forRoot(),
BrowserModule,
MyDatePickerModule,
FormsModule,
ReactiveFormsModule,
DynamicFormModule,
HttpModule,
DragulaModule,
UuidModule,
AppRoutingModule,
TranslateModule.forRoot({
provide: TranslateLoader,
useFactory: (createTranslateLoader),
deps: [Http]
}),
StoreModule.provideStore(reducer),
StoreDevtoolsModule.instrumentOnlyWithExtension(),
// Initializing effects
EffectsModule.run(fromEffects.AuthEffects),
EffectsModule.run(fromEffects.CircuitEffects),
ResponsiveModule,
Angulartics2Module.forRoot([ Angulartics2GoogleAnalytics ]),
],
providers: [
Title,
Providers,
NotificationsService
],
bootstrap: [AppComponent]
})
export class AppModule { }
This my Packages.json file :
{
"name": "migrationProject",
"version": "2.0",
"license": "MIT",
"#angular/cli": {},
"scripts": {
"start": "node node_modules/#angular/cli/bin/ng s --env=source",
"start:local": "node node_modules/#angular/cli/bin/ng s --
env=local",
"build": "node node_modules/#angular/cli/bin/ng build --dev --
env=source",
"build:prod": "node node_modules/#angular/cli/bin/ng build --prod --
env=prod",
"deploy": "./gradlew deploy",
"deploy:win": "gradlew.bat deploy",
"lint": "tslint \"src/**/*.ts\"",
"test": "node node_modules/#angular/cli/bin/ng test",
"pree2e": "webdriver-manager update",
"e2e": "protractor",
"i18n": "./node_modules/.bin/ng-xi18n"
},
"private": true,
"dependencies": {
"#angular/animations": "4.3.0 ",
"#angular/common": "4.3.0 ",
"#angular/compiler": "4.3.0 ",
"#angular/core": "4.3.0 ",
"#angular/forms": "4.3.0 ",
"#angular/http": "4.3.0 ",
"#angular/platform-browser": "4.3.0 ",
"#angular/platform-browser-dynamic": "4.3.0 ",
"#angular/router": "4.3.0 ",
"#ngrx/core": "^1.2.0",
"#ngrx/effects": "^2.0.0",
"#ngrx/store": "^2.2.1",
"#swimlane/ngx-charts": "4.4.0",
"#types/file-saver": "0.0.1",
"#types/jszip": "0.0.33",
"#types/lodash": "4.14.30",
"#types/node-uuid": "0.0.28",
"angular-2-daterangepicker": "^1.1.32",
"angular2-bootstrap-switch": "^0.2.3",
"angular2-jwt": "^0.1.28",
"angular2-notifications": "0.4.53",
"angular2-signaturepad": "^2.8.0",
"angular2-tag-input": "^1.2.3",
"angulartics2": "<= 1.6.4",
"chart.js": "^2.7.2",
"classlist.js": "^1.1.20150312",
"core-js": "^2.4.1",
"d3": "^4.6.0",
"dragula": "^3.7.2",
"file-saver": "^1.3.3",
"font-awesome": "^4.7.0",
"lie": "^3.3.0",
"lodash": "^4.14.17",
"moment": "2.18.1",
"mydatepicker": "^2.0.20",
"ng-qrcode": "^1.1.2",
"ng2-ckeditor": "^1.2.2",
"ng2-device-detector": "^1.0.0",
"ng2-dragula": "^1.2.1",
"ng2-file-upload": "^1.2.1",
"ng2-img-cropper": "^0.8.0",
"ng2-opd-popup": "^1.1.21",
"ng2-pdf-viewer": "^3.0.8",
"ng2-responsive": "^0.8.4",
"ng2-translate": "^4.2.0",
"ng2-uuid": "0.0.3",
"ngx-bootstrap": "^2.0.0",
"ngx-drag-drop": "^1.1.0",
"ngx-infinite-scroll": "^0.8.4",
"ngx-popover": "0.0.16",
"node-uuid": "^1.4.8",
"pdf.js": "^0.1.0",
"pdfjs-dist": "^1.9.489",
"rxjs": "^5.4.2",
"ts-helpers": "^1.1.1",
"zone.js": "^0.8.14"
},
"devDependencies": {
"#angular/cli": "^1.4.3",
"#angular/compiler-cli": "^4.3.0 ",
"#angular/platform-server": "4.3.0 ",
"#ngrx/store-devtools": "^3.2.2",
"#types/chai": "^3.4.34",
"#types/jasmine": "2.5.38",
"#types/node": "^6.0.51",
"angular2-template-loader": "^0.6.2",
"awesome-typescript-loader": "^3.5.0",
"base64-js": "^1.2.1",
"bootstrap": "^3.3.7",
"bootstrap-sass": "^3.3.7",
"codelyzer": "^2.0.0-beta.4",
"coffeescript": "^2.4.1",
"css-loader": "^0.26.4",
"extract-text-webpack-plugin": "^2.0.0-beta.5",
"file-loader": "^3.0.1",
"html-webpack-plugin": "^3.2.0",
"ieee754": "^1.1.8",
"jasmine-core": "^2.5.2",
"jasmine-spec-reporter": "^3.2.0",
"jszip": "3.1.3",
"karma": "^1.3.0",
"karma-chrome-launcher": "^2.0.0",
"karma-cli": "^1.0.1",
"karma-coverage": "^1.1.1",
"karma-jasmine": "^1.0.2",
"karma-mocha-reporter": "^2.2.2",
"karma-phantomjs-launcher": "^1.0.2",
"karma-remap-istanbul": "^0.6.0",
"karma-sourcemap-loader": "^0.3.7",
"karma-webpack": "1.8.0",
"ngrx-store-freeze": "^0.1.6",
"ngx-bootstrap": "^1.6.5",
"node-sass": "^4.11.0",
"protractor": "^5.1.1",
"raw-loader": "^2.0.0",
"reflect-metadata": "^0.1.9",
"sass-loader": "^4.1.1",
"sockjs-client": "^1.1.4",
"style-loader": "^0.13.2",
"ts-helpers": "^1.1.2",
"ts-node": "^1.7.0",
"tslint": "^4.3.1",
"tslint-loader": "^3.3.0",
"typescript": "~2.3.3",
"url-loader": "^1.1.2",
"webpack": "^4.3.0",
"webpack-dev-server": "^2.11.5"
}
}
How to fix this error...
Import services
// Does not use the mapValuesToArray function
export function mapValuesToArray (obj){
return [
Object.keys(obj).map(key => obj[key])
];
}
// Replace the following expression :
export const Artefacts = [
...mapValuesToArray(components),
ImageCropperComponent
];
// With the following expression :
export const Artefacts = [
...components,
ImageCropperComponent
];
// for that you should change the following import :
import * as components from './components';
// to this expression :
import {components} from './components';
// you need also to exports the components in your index.ts as follows :
import {SpinnerComponent} from "./spinner/spinner.component";
import {AboutComponent} from "./about/about.component";
export const components = [AboutComponent, SpinnerComponent];
// does the same for the following imports :
import * as services from './services';
import * as guards from './guards';
// In the other hand
unistall webpack library, because it is offer by #angular/cli
Currently I have an angular component x.component.html which contains the following (using angular material):
<div class="example-container mat-elevation-z8">
<div class="example-header">
<mat-form-field>
<input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">
</mat-form-field>
</div>
<mat-table #table [dataSource]="dataSource">
<ng-container matColumnDef="farbeKey">
<mat-header-cell *matHeaderCellDef> farbeKey </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.farbeKey}} </mat-cell>
</ng-container>
....
Furthermore I have the component x.component.ts which looks like this:
import { BrowserModule } from '#angular/platform-browser';
import { Component, OnInit } from '#angular/core';
import { User } from '../models/user.model';
import { OrgtService } from './orgt.service';
#Component({
selector: 'x-component',
styleUrls: ['x.component.css'],
templateUrl: 'x.component.html',
})
export class XComponent implements OnInit {
users: User[] = []
constructor(private xService: XService) {
}
displayedColumns = ['c1', 'c2', 'c3', 'c4'];
dataSource = new MatTableDataSource(this.users);
applyFilter(filterValue: string) {
filterValue = filterValue.trim(); // Remove whitespace
filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults to lowercase matches
this.dataSource.filter = filterValue;
}
public ngOnInit() {
this.xService.getUsers()
.subscribe(
(users) => {
this.users = users;
}
);
}
}
But the problem is that If try to access that in the browser I got the following error message (this is only an excerpt):
Uncaught Error: Bootstrap's JavaScript requires jQuery
at scripts.bundle.js:8
(anonymous) # scripts.bundle.js:8
compiler.js:485 Uncaught Error: Template parse errors:
'mat-form-field' is not a known element:
1. If 'mat-form-field' is an Angular component, then verify that it is part of this module.
2. If 'mat-form-field' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '#NgModule.schemas' of this component to suppress this message. ("
<div class="example-header">
[ERROR ->]<mat-form-field>
<input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter"): ng:///AppModule/OrgtComponent.html#3:4
Can't bind to 'dataSource' since it isn't a known property of 'mat-table'.
1. If 'mat-table' is an Angular component and it has 'dataSource' input, then verify that it is part of this module.
2. If 'mat-table' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '#NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '#NgModule.schemas' of this component. ("
</div>
Here is my package.json file:
{
"name": "portal-app",
"version": "0.0.0",
"license": "MIT",
"scripts": {
"ng": "ng",
"start": "ng serve --proxy-config proxy.config.json",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"#angular/animations": "^5.0.0",
"#angular/cdk": "^5.2.2",
"#angular/common": "^5.0.0",
"#angular/compiler": "^5.0.0",
"#angular/core": "^5.0.0",
"#angular/forms": "^5.0.0",
"#angular/http": "^5.0.0",
"#angular/material": "^5.2.2",
"#angular/platform-browser": "^5.0.0",
"#angular/platform-browser-dynamic": "^5.0.0",
"#angular/router": "^5.0.0",
"bootstrap": "^3.3.7",
"core-js": "^2.4.1",
"rxjs": "^5.5.2",
"zone.js": "^0.8.14"
},
"devDependencies": {
"#angular/cli": "1.6.3",
"#angular/compiler-cli": "^5.0.0",
"#angular/language-service": "^5.0.0",
"#types/jasmine": "~2.5.53",
"#types/jasminewd2": "~2.0.2",
"#types/node": "~6.0.60",
"codelyzer": "^4.0.1",
"jasmine-core": "~2.6.2",
"jasmine-spec-reporter": "~4.1.0",
"karma": "~1.7.0",
"karma-chrome-launcher": "~2.1.1",
"karma-cli": "~1.0.1",
"karma-coverage-istanbul-reporter": "^1.2.1",
"karma-jasmine": "~1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~5.1.2",
"ts-node": "~3.2.0",
"tslint": "~5.7.0",
"typescript": "~2.4.2"
}
}
If I correctly understand I'm missing somehow / somewhere the definition of the mat-... tags but I don't know where I need to put what kind of definition? Can someone enlighten me a little bit?
Update (1):
After installing jquery and changing the .angular-cli.json file the error message has change as expected to remove the JQuery issue like this:
ncaught Error: Template parse errors:
'mat-form-field' is not a known element:
1. If 'mat-form-field' is an Angular component, then verify that it is part of this module.
2. If 'mat-form-field' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '#NgModule.schemas' of this component to suppress this message. ("
<div class="example-header">
[ERROR ->]<mat-form-field>
<input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter"): ng:///AppModule/OrgtComponent.html#3:4
Can't bind to 'dataSource' since it isn't a known property of 'mat-table'.
1. If 'mat-table' is an Angular component and it has 'dataSource' input, then verify that it is part of this module.
2. If 'mat-table' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '#NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '#NgModule.schemas' of this component. ("
</div>
Also I have added the imports based on Juan's suggestions.
Update (2):
After integrating each answer my app starts and compiles without any issue.
Now I got the following:
ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'x'
Error: Cannot match any routes. URL Segment: 'x'
Update (3):
So after fixing the app.routing.module.ts like this:
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { UserComponent } from './user/user.component';
import {AddUserComponent} from './user/add-user.component';
import { XComponent} from './x/x.component';
const routes: Routes = [
{ path: 'users', component: UserComponent },
{ path: 'add', component: AddUserComponent },
{ path: 'x', component: XComponent }
];
#NgModule({
imports: [
RouterModule.forRoot(routes)
],
exports: [
RouterModule
],
declarations: []
})
export class AppRoutingModule { }
I got another step further and got this:
ERROR Error: Uncaught (in promise): Error: StaticInjectorError[XService]:
StaticInjectorError[XService]:
NullInjectorError: No provider for XService!
Error: StaticInjectorError[XService]:
StaticInjectorError[XService]:
NullInjectorError: No provider for XService
You need to import the following in your app.module.ts:
import {MatInputModule} from '#angular/material/input';
import {MatTableModule} from '#angular/material/table';
import {FormsModule} from '#angular/forms';
And in your x.component.ts:
import {MatTableDataSource} from '#angular/material';
It's impossible to have jquery as a dependancie of angular material.
The problem of jquery and angular mat-form-field are tow seperate problems.
It's seem that you install Bootstrap's theme, which require jquery.
So install jquery npm install jquery --save
add the typings: npm install --save-dev #types/jquery
And add the script to angular-cli.json:
"apps": [{
...
"scripts": [
"../node_modules/jquery/dist/jquery.min.js",
],
...
}]
To fix mat-form-field issue you need to import this module in your app.module.ts:
import {MatInputModule} from '#angular/material/input';
...
#NgModule({
...,
imports: [
...,
MatInputModule,
...
],
...
})
export class AppModule { }
One convenient way to handle angular material import is to create a custom module for material component: https://medium.com/#armno/creating-a-custom-material-module-in-angular-ee6a5e925d30
install jquery
npm install jquery
"../node_modules/jquery/dist/jquery.min.js",
add this line into "scripts": [] in angular-cli.json
now check you module.
MatTableModule and MatFormModule imported in you module
Update
replace in your xcomponent
#Component({
selector: 'x-component',
styleUrls: ['x.component.css'],
templateUrl: 'x.component.html',
providers:[xService] // need to set provider
})
I am new to the angular. I have made the set up for angular project.First time when i fired the ng serve --open command , it opened the url and was working fine. After that i have installed angular material .Now if i run the application it is taking me the new browser tab. But showing compilation error. Could someone please help me to sort out the exact issue. I was trying this past 3 hours. please help.
npm install --save #angular/material #angular/cdk
npm install --save #angular/animations
npm install --save hammerjs
npm install --save #angular/flex-layout#latest
my app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
import { MaterialModule } from '#angular/material';
import { FlexLayoutModule } from '#angular/flex-layout';
import { AppComponent } from './app.component';
import 'hammerjs';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
MaterialModule,
FlexLayoutModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
my package.json
{
"name": "con-fusion",
"version": "0.0.0",
"license": "MIT",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"#angular/animations": "^4.4.3",
"#angular/cdk": "^2.0.0-beta.11",
"#angular/common": "^4.2.4",
"#angular/compiler": "^4.2.4",
"#angular/core": "^4.2.4",
"#angular/flex-layout": "^2.0.0-beta.9",
"#angular/forms": "^4.2.4",
"#angular/http": "^4.2.4",
"#angular/material": "^2.0.0-beta.11",
"#angular/platform-browser": "^4.2.4",
"#angular/platform-browser-dynamic": "^4.2.4",
"#angular/router": "^4.2.4",
"core-js": "^2.4.1",
"hammerjs": "^2.0.8",
"rxjs": "^5.4.2",
"zone.js": "^0.8.14"
},
"devDependencies": {
"#angular/cli": "1.4.3",
"#angular/compiler-cli": "^4.2.4",
"#angular/language-service": "^4.2.4",
"#types/jasmine": "~2.5.53",
"#types/jasminewd2": "~2.0.2",
"#types/node": "~6.0.60",
"codelyzer": "~3.1.1",
"jasmine-core": "~2.6.2",
"jasmine-spec-reporter": "~4.1.0",
"karma": "~1.7.0",
"karma-chrome-launcher": "~2.1.1",
"karma-cli": "~1.0.1",
"karma-coverage-istanbul-reporter": "^1.2.1",
"karma-jasmine": "~1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~5.1.2",
"ts-node": "~3.2.0",
"tslint": "~5.3.2",
"typescript": "~2.3.3"
}
}
My app.component.html
<div style="text-align:center">
<h1>
Welcome to {{title}}!
</h1>
<img width="300" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg==">
<md-toolbar color="primary"> <span>Ristorante Con Fusion</span> </md-toolbar>
</div>
<h2>Here are some links to help you start: </h2>
<ul>
<li>
<h2><a target="_blank" rel="noopener" href="https://angular.io/tutorial">Tour of Heroes</a></h2>
</li>
<li>
<h2><a target="_blank" rel="noopener" href="https://github.com/angular/angular-cli/wiki">CLI Documentation</a></h2>
</li>
<li>
<h2><a target="_blank" rel="noopener" href="https://blog.angular.io/">Angular blog</a></h2>
</li>
</ul>
My style.scss
#import '~#angular/material/prebuilt-themes/deeppurple-amber.css';
body {
padding: 0;
margin: 0;
font-family: Roboto, sans-serif;
}
See Getting Started With Angular Material 2
(September 4, 2017)
Custom Material Module
Prior to Angular Material 2 Beta 3, there was a global MaterialModule
that could be imported in the app module to make the components
available. The downside to that is that tree-shaking is not efficient
enough to remove all the unused code.
MaterialModule has therefore been deprecated in favor of defining a
project-specific custom material module where you import and export
only the needed components. Here’s what our module can look like:
Unfortunately the official guide is a not as explicit as the above article. You need to go through each component you use and import the module for for it, then add it to the imports section of AppModule.
Looks like you are just using Toolbar, so the only module you need is MdToolbarModule.
import { MdToolbarModule } from '#angular/material';
#NgModule({
imports: [
...
MdToolbarModule,
],
Essentially, as the article above explains, you 'roll-your-own' MaterialModule. The main purpose seems to be avoiding deploying of unused material components in your app.
Actually, MaterialModule is not importable anymore, you need to import the only module that you want, you can see this info here:
CHANGELOG.md#breaking-changes
So, if you want material, import only the component module that you want, you can see the components list here:
https://material.angular.io/components
as for example, if I want material input, you go to API tab see what you want to import:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
import { MatMenuModule} from '#angular/material';
import { FlexLayoutModule } from '#angular/flex-layout';
import { AppComponent } from './app.component';
import 'hammerjs';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
MatMenuModule,
FlexLayoutModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
And this is the official plunker example:
http://plnkr.co/edit/o077B6uEiiIgkC0S06dd?p=preview
Anyway, I don't see where you are using the material component in your HTML, so not sure which one you want to use.
I am receiving the above error in the console of the Chrome browser, and I am at a loss as where to look and what too do. The complete stack trace looks like this:
ERROR TypeError: Cannot read property 'index' of null
at ComponentFactory_.create (http://localhost:63770/node_modules/#angular/core/bundles/core.umd.js:9896:101)
at ComponentFactoryBoundToModule.create (http://localhost:63770/node_modules/#angular/core/bundles/core.umd.js:3434:29)
at ApplicationRef_.bootstrap (http://localhost:63770/node_modules/#angular/core/bundles/core.umd.js:5017:57)
at eval (http://localhost:63770/node_modules/#angular/core/bundles/core.umd.js:4806:79)
at Array.forEach (native)
at PlatformRef_._moduleDoBootstrap (http://localhost:63770/node_modules/#angular/core/bundles/core.umd.js:4806:42)
at eval (http://localhost:63770/node_modules/#angular/core/bundles/core.umd.js:4768:27)
at ZoneDelegate.invoke (http://localhost:63770/node_modules/zone.js/dist/zone.js:365:26)
at Object.onInvoke (http://localhost:63770/node_modules/#angular/core/bundles/core.umd.js:4135:37)
at ZoneDelegate.invoke (http://localhost:63770/node_modules/zone.js/dist/zone.js:364:32)
at Zone.run (http://localhost:63770/node_modules/zone.js/dist/zone.js:125:43)
at http://localhost:63770/node_modules/zone.js/dist/zone.js:758:57
at ZoneDelegate.invokeTask (http://localhost:63770/node_modules/zone.js/dist/zone.js:398:31)
at Object.onInvokeTask (http://localhost:63770/node_modules/#angular/core/bundles/core.umd.js:4126:37)
at ZoneDelegate.invokeTask (http://localhost:63770/node_modules/zone.js/dist/zone.js:397:36)
My app.module.ts is this:
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { GPAEnterpriseAppComponent } from './gpaenterprise-app.component';
#NgModule({
imports: [
BrowserModule
],
declarations: [
GPAEnterpriseAppComponent
],
providers: [],
bootstrap: [GPAEnterpriseAppComponent]
})
export class AppModule { }
The referenced app component looks like this:
import { Component } from '#angular/core';
#Component({
selector: 'gpa-enterprise-app',
template: '<h1>We are here</h1>'
})
export class GPAEnterpriseAppComponent {
}
I do not know if it is needed, but here is the package.json:
"version": "1.0.0",
"name": "gpa_enterprise",
"private": true,
"devDependencies": {
"gulp": "^3.9.1",
"typescript": "^2.3.2",
"typings": "^2.1.1"
},
"dependencies": {
"#angular/animations": "^4.1.2",
"#angular/common": "^4.1.2",
"#angular/compiler": "^4.1.2",
"#angular/core": "^4.1.2",
"#angular/forms": "^4.1.2",
"#angular/http": "^4.1.2",
"#angular/material": "^2.0.0-beta.3",
"#angular/platform-browser": "^4.1.2",
"#angular/platform-browser-dynamic": "^4.1.2",
"#angular/router": "^4.1.2",
"#angular/upgrade": "^4.1.2",
"angular2-in-memory-web-api": "^0.0.21",
"core-js": "^2.4.1",
"primeng": "^4.0.0",
"reflect-metadata": "^0.1.10",
"rxjs": "^5.4.0",
"systemjs": "^0.20.12",
"zone.js": "^0.8.10"
},
"scripts": {
"postinstall": "typings install",
"typings": "typings",
"cmd": "npm typescript"
}
}
.csproj typescript configurations, as requested:
<PropertyGroup>
<TypeScriptToolsVersion>1.8</TypeScriptToolsVersion>
<TypeScriptRemoveComments>false</TypeScriptRemoveComments>
<TypeScriptSourceMap>true</TypeScriptSourceMap>
<TypeScriptTarget>ES5</TypeScriptTarget>
<TypeScriptJSXEmit>None</TypeScriptJSXEmit>
<TypeScriptCompileOnSaveEnabled>True</TypeScriptCompileOnSaveEnabled>
<TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
<TypeScriptNoImplicitAny>False</TypeScriptNoImplicitAny>
<TypeScriptModuleKind>System</TypeScriptModuleKind>
<TypeScriptOutFile />
<TypeScriptOutDir />
<TypeScriptGeneratesDeclarations>False</TypeScriptGeneratesDeclarations>
<TypeScriptNoEmitOnError>True</TypeScriptNoEmitOnError>
<TypeScriptMapRoot />
<TypeScriptSourceRoot />
<TypeScriptExperimentalDecorators>True</TypeScriptExperimentalDecorators>
<TypeScriptEmitDecoratorMetadata>True</TypeScriptEmitDecoratorMetadata>
</PropertyGroup>
The .csproj had
<TypeScriptToolsVersion>1.8</TypeScriptToolsVersion>,
but I had updated to 2.3. Changing the above line to reflect this has fixed the error I was receiving.
Not really familiar with .csproj files, but I reckon they function as the tsconfig. I would try setting:
<TypeScriptModuleKind>es2015</TypeScriptModuleKind>
Do not know for sure if you need to cap it for your IDE.