error NG8001: 'mat-form-field' is not a known element - mat

Currently I am struggling with an error after try to use a few mat components like "mat-form-field" or "mat-date-range-input" etc..
I've already imported them in the app.module file as I always do with these kind of component, but I get many errors like this:
If 'mat-form-field' is an Angular component, then verify that it is part of this module
If 'mat-label' is an Angular component, then verify that it is part of this module.
I have to say that in the same project I am using mat-tab-group and mat-tab etc... and I have not any errors with them.
These is my code:
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AngularMaterialModule } from './angular-material.module/angular-material.module.module';
import { MatButtonToggleModule } from '#angular/material/button-toggle';
import { MatSlideToggleModule } from '#angular/material/slide-toggle';
import { MatCardModule } from '#angular/material/card';
import { MatFormFieldModule } from '#angular/material/form-field';
import { MatInputModule } from '#angular/material/';
import { MatIconModule } from '#angular/material/icon';
import { ClipboardModule } from '#angular/cdk/clipboard';
#NgModule({
declarations: [], // I've omitted this part because is not relevant to this issue
imports: [
BrowserModule,
AppRoutingModule,
AngularMaterialModule,
MatProgressSpinnerModule,
MatButtonToggleModule,
MatSlideToggleModule,
MatCardModule,
MatFormFieldModule,
MatInputModule,
MatIconModule,
ClipboardModule
],
providers: [{provide: LocationStrategy, useClass: PathLocationStrategy}],
bootstrap: [AppComponent]
})
export class AppModule { }
And my component : create.report.component.html
<mat-form-field appearance="fill">
<mat-label>Enter a date range</mat-label>
<mat-date-range-input [formGroup]="reportForm" [rangePicker]="picker">
<input matStartDate formControlName="from" placeholder="Start date">
<input matEndDate formControlName="to" placeholder="End date">
</mat-date-range-input>
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-date-range-picker #picker></mat-date-range-picker>
</mat-form-field>
create.report.component.ts
import { Component, OnInit } from '#angular/core';
import { FormBuilder, Validators, FormGroup, FormArray, FormControl } from '#angular/forms';
import { Router } from '#angular/router';
#Component({
selector: 'app-report',
templateUrl: './create.report.component.html'
})
export class CreateReportComponent implements OnInit {
reportForm = new FormGroup({
from: new FormControl(),
to: new FormControl()
});
constructor(
private router: Router,
private fb: FormBuilder) {
this.buildForm();
}
ngOnInit(): void {
}
buildForm() {
// console.log('***buildForm this.hmService***', this.hmService);
this.reportForm = this.fb.group( {
from : [ '', [Validators.required, Validators.minLength(5)]],
to: [ '', [Validators.required, Validators.minLength(5)]],
published : [ '', [Validators.required, Validators.minLength(5)]]
});
}
}

Ok, finally I solved!
With this line I fix the issue I had with material components. Now I can use them in my create.report.component .
import { CreateReportComponent } from './pages/report/create/create.report.component';

Related

I am fatch data by username from django API using angular4

this is my anglar4 creating app name as search i want to fatch data from django rest API. I want that when i give username it give me only this username data.
app.components.tc
import { Component } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
username:string = '';
constructor(private httpClient:HttpClient){}
onNameKeyUP(event:any){
this.username = event.target.value;
}
getProfile(){
console.log(this.username)
this.httpClient.get("http://127.0.0.1:8000/loginAdmin/?username=${this.username}")
.subscribe(
(data:any[]) => {
console.log(data);
}
)
}
}
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { HttpClientModule } from '#angular/common/http';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.components.html
it is my simlple Html which is use to send username from Django API
<input type="text" (keyup)="onNameKeyUP($event)">
<button (click)="getProfile()">Get Profile</button>
Try this:
app.component.ts
import { Component, OnInit } from '#angular/core';
import { FormControl } from '#angular/forms';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import {
filter,
map,
switchMap,
debounceTime,
distinctUntilChanged,
} from 'rxjs/operators';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
profile$: Observable<any>;
ctrl = new FormControl();
constructor(private httpClient: HttpClient) {}
ngOnInit() {
this.profile$ = this.ctrl.valueChanges.pipe(
filter(v => v.length > 2),
debounceTime(400),
distinctUntilChanged(),
switchMap(username =>
this.httpClient.get(
`http://127.0.0.1:8000/loginAdmin/?username=${username}`,
),
),
);
}
}
app.component.html
<input [formControl]="ctrl">
<div> {{ profile$ | async | json }} </div>
app.module.ts
import { ReactiveFormsModule } from '#angular/forms';
#NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
ReactiveFormsModule,
...
],
providers: [...],
bootstrap: [AppComponent],
})
export class AppModule {
constructor() {}
}

Module has no exported module named PeopleService - Ionic

I have been folllowing the ionic tutorial:
10 Minutes with Ionic 2: Calling an API
Typescript Error
Module '"C:/Users/grace/imaginemai/client/apiApp/src/providers/people->service/people-service"' has no exported member 'PeopleSevice'.
C:/Users/grace/imaginemai/client/apiApp/src/pages/home/home.ts
import { NavController } from 'ionic-angular';
import {PeopleSevice} from >'C:\Users\grace\imaginemai\client\apiApp\src\providers\people-> >service\people-service';
I am not sure what I am doing wrong. I noticed that there were possible errors with the original tutorial so I made some amendments as per a correction posted in the comments: https://github.com/ah3243/ionic2ApiExample/blob/master/src/providers/people-search.ts
I am still having issues - I've followed the tutorial but used my own API from a blog I am developing with Django. So although the ionic app is called peopleservice, I am expecting it to produce blog posts. The code is pasted below. Please could someone tell me what I am doing wrong.
Thanks in advance.
people-service.ts:
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
/*
Generated class for the PeopleServiceProvider provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
#Injectable()
export class PeopleService {
data1: any;
constructor(public http: Http) {
console.log('Hello PeopleService Provider');
}
load() {
if (this.data1) {
return Promise.resolve(this.data1);
}
//dont have the data yet
return new Promise(resolve => {
this.http.get('localhost:8000/posts/')
.map(res => res.json())
.subscribe(data => {
this.data1 = data.results;
resolve(this.data1);
});
});
}
}
home.ts:
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import {PeopleSevice} from 'C:\\Users\\grace\\imaginemai\\client\\apiApp\\src\\providers\\people-service\\people-service';
#Component({
selector: 'page-home',
templateUrl: 'home.html',
providers: [PeopleSevice]
})
export class HomePage {
public posts: any;
constructor(public navCtrl: NavController, public peopleService: PeopleService) {
this.loadPosts();
}
loadPosts() {
this.PeopleService.load()
.then(data1 => {
this.posts = data1;
})
}
}
app.module.ts:
import { NgModule, ErrorHandler } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { AboutPage } from '../pages/about/about';
import { ContactPage } from '../pages/contact/contact';
import { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
/*import { PeopleService } from 'C:\\Users\\grace\\imaginemai\\client\\apiApp\\src\\providers\\people-service\\people-service';*/
#NgModule({
declarations: [
MyApp,
AboutPage,
ContactPage,
HomePage,
TabsPage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
AboutPage,
ContactPage,
HomePage,
TabsPage
],
providers: [
/*StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
PeopleService*/
]
})
export class AppModule {}
app.component.ts:
import { Component } from '#angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { TabsPage } from '../pages/tabs/tabs';
import { PeopleService } from 'C:\\Users\\grace\\imaginemai\\client\\apiApp\\src\\providers\\people-service\\people-service';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage:any = TabsPage;
constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
statusBar.styleDefault();
splashScreen.hide();
});
}
}
home.html:
<ion-header>
<ion-navbar *navbar>
<ion-title>
Home
</ion-title>
</ion-navbar>
</ion-header>
<ion-content class="home">
<ion-list>
<ion-item *ngFor="let post of posts">
<h2>{{post.title}}</h2>
<p>{{post.text}}</p>
</ion-item>
</ion-list>
</ion-content>
folder structure:
blog
>client
>apiApp
>src
>app
>app.component.ts
>app.html
>app.module.ts
>app.scss
>main.ts
>pages
>providers
>people-service
>people-service.ts
You have to use relative paths for importing.
import {PeopleSevice} from 'C:\\Users\\grace\\imaginemai\\client\\apiApp\\src\\providers\\people-service\\people-service';
This kind of absolute path will not work.
Try:
import {PeopleSevice} from '../../providers/people-service/people-service';
This is the relative path from the current file.

Unit testing errors for ngModel, custom pipe and modal [duplicate]

This question already has answers here:
angular2 testing: Can't bind to 'ngModel' since it isn't a known property of 'input'
(2 answers)
Closed 5 years ago.
Trying to test my Angular application, but when trying to create my component I get multiple errors.
Can't bind to 'ngModel' since it isn't a known property of 'input'.
The pipe 'sortOnLike' could not be found.
'app-edit-message-modal' is not a known element:
If 'app-edit-message-modal' is an Angular component, then verify that it is part of this module.
If 'app-edit-message-modal' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '#NgModule.schemas' of this component to suppress this message.
Answers to similar errors haven't helped me much.
dashboard.spec.ts
import { async, ComponentFixture, TestBed } from '#angular/core/testing';
import { Router } from "#angular/router";
import { MockAF } from "../../providers/mockAf";
import { AF } from "../../providers/af";
import { DashboardComponent } from './dashboard.component';
describe('DashboardComponent', () => {
let component: DashboardComponent;
let fixture: ComponentFixture<DashboardComponent>;
let routerStub;
beforeEach(async(() => {
routerStub = {
navigate: jasmine.createSpy('navigate')
};
TestBed.configureTestingModule({
declarations: [ DashboardComponent ],
providers: [
{ provide: AF, useClass: MockAF },
{ provide: Router, useValue: routerStub },
],
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(DashboardComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
Snippets from HTMLfile:
dashboard.component.html
<figure class="highlight">
<input type="textarea" class="message-text" [(ngModel)]="newMessage"
(keyup.enter)="sendMessage()">
<a class="send-message" (click)="sendMessage()">SEND</a>
</figure>
<a *ngIf="isMe(message.email)" type='edit' class='edit-text' style="cursor:
pointer;" (click)="show(message.$key, message.message)">Edit</a>
<!-- Modal (popup) for editing messages belonging to you -->
<app-edit-message-modal>
// modal form
</app-edit-message-modal>
<div *ngFor="let message of afService.messages | async |
sortOnLike:'votes':false">
snippets from dashboard.component.ts
import { Component, OnInit, AfterViewChecked, ElementRef, ViewChild } from
'#angular/core';
import { ActivatedRoute, Router } from '#angular/router';
import { AF } from '../../providers/af';
import { FirebaseListObservable, AngularFire } from 'angularfire2';
import { Bubble } from './bubble';
import { EditMessageModalComponent } from '../edit-message-modal/edit-
message-modal.component';
show(key: string, message: string): void {
this.modalMessage = message;
this.modalMessageKey = key;
this.modal.show();
}
hide(): void {
this.modalMessage = null;
this.modalMessageKey = null;
this.modal.hide();
}
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 { RouterModule, Routes } from '#angular/router';
import { AngularFireModule } from 'angularfire2';
import { AppComponent } from './app.component';
import { RegistrationPageComponent } from './registration-page/registration-
page.component';
import { LoginPageComponent } from './login-page/login-page.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { AF } from '../providers/af';
import { FrontscreenComponent } from './frontscreen/frontscreen.component';
import { StudentDashboardComponent } from './student-dashboard/student-
dashboard.component';
import { LecturerDashboardComponent } from './lecturer-dashboard/lecturer-
dashboard.component';
import { firebaseConfig } from './config';
import { EditCourseModalComponent } from './edit-course-modal/edit-course-
modal.component';
import { EditMessageModalComponent } from './edit-message-modal/edit-
message-modal.component';
import { SortOnLikePipe } from './sort-on-like.pipe'
#NgModule({
declarations: [
AppComponent,
RegistrationPageComponent,
LoginPageComponent,
DashboardComponent,
FrontscreenComponent,
StudentDashboardComponent,
LecturerDashboardComponent,
EditCourseModalComponent,
EditMessageModalComponent,
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
AngularFireModule.initializeApp(firebaseConfig),
RouterModule.forRoot(routes),
SortOnLikePipe
],
providers: [AF],
bootstrap: [AppComponent],
})
export class AppModule { }
in your test, inside beforeEach block. You need to add the following to TestBed.configureTestingModule
All used pipes, components and directives have to be declared. in your case: SortOnLikePipe and EditMessageModalComponent
all used modules have to be imported. in your case: FormsModule
all needed services have to be provided
Here are the ones you are missing:
I'd imagine you might be missing more..
TestBed.configureTestingModule({
declarations: [ DashboardComponent, SortOnLikePipe, EditMessageModalComponent ],
imports:[FormsModule]
providers: [
{ provide: AF, useClass: MockAF },
{ provide: Router, useValue: routerStub },
],
})

Angular 2 unit test case is not working for services with external module configuration

If I create a module with services using #Inject method is not working with Angular 2 Testbed Unit test cases. It is throwing No Provider for AppService Error.
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 { AppService } from './app.service';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule
],
providers: [
{provide:'AppService',useClass:AppService}
],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
import { Component, Inject } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app works!';
constructor(#Inject('AppService') private appService) {}
getName() {
this.title = this.appService.getName();
}
setName(name) {
this.appService.setName(name);
}
}
app.service.ts
import { Injectable } from '#angular/core';
#Injectable()
export class AppService {
private name = 'dummy';
public getName() {
return this.name;
}
public setName(name) {
console.log("ser", name);
this.name = name;
}
}
app.component.spec.ts
import { Injectable} from '#angular/core';
import { TestBed, async, inject } from '#angular/core/testing';
import { AppComponent } from './app.component';
import { FormsModule } from '#angular/forms';
import { AppService } from './app.service';
describe('AppComponent', () => {
let fixture, comp, appService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [FormsModule],
declarations: [
AppComponent
],
providers: [AppService]
}).compileComponents();
fixture = TestBed.createComponent(AppComponent);
comp = fixture.debugElement.componentInstance;
appService = fixture.debugElement.injector.get(AppService);
});
it('should create the app', async(() => {
expect(comp).toBeTruthy();
}));
});
try adding providers: [AppService] in #Component in app.component.ts as below
#Component({
providers: [AppService],
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})

Unit testing component with angulartics2 - Can't bind to 'angularticsCategory' since it isn't a known property of 'div'

I am starting a project using Angular 2.0.0 stable release created with angular-cli 1.0.0-beta.14 and angulartics 1.1.9.
I am trying to start some simple unit testing and am recording clicks on a button component
<div class="sidebar-toggle" (click)="toggleSideBar()" angulartics2On="click" angularticsCategory="{{ expanded ? 'expand': 'collapse' }}">
//divContent
</div>
However, when I run the test which is simple bootstrapping the component I get the error
Can't bind to 'angularticsCategory' since it isn't a known property of 'div'
The app works fine but the issue only comes up in testing. I can't find an example where someone is having the same error in testing. I know I am missing something like not properly exposing the angulartics2 lib in my karma.conf OR not injecting the Angulartics or a mocked dependency in my Testbed config.
Really lost and would like to know if anyone is having similar problems. Can provide more code snippets if needed but don't want to dump the whole file nobody's got time to read that!
In my case to get Angulatics2 unit tests to work I had to:
1) Import Angulartics2Module into the root app.module.ts
import { Angulartics2Module } from 'angulartics2';
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { environment } from '../environments/environment';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
#NgModule({
declarations: [
AppComponent,
HeaderComponent,
],
imports: [
BrowserModule,
Angulartics2Module.forRoot({ developerMode: !environment.production }),
AppRoutingModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
2) Enable tracking in app.component.ts
import { Angulartics2GoogleGlobalSiteTag } from 'angulartics2/gst';
import { Component } from '#angular/core';
import { RouterOutlet } from '#angular/router';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent {
constructor(
public angulartics2GoogleGlobalSiteTag: Angulartics2GoogleGlobalSiteTag,
) {
this.angulartics2GoogleGlobalSiteTag.startTracking();
}
}
3) Import Angulartics2Module.forRoot() and Angulartics2 provider in to app.component.spec.ts
import { HttpClientTestingModule } from '#angular/common/http/testing';
import { TestBed, async } from '#angular/core/testing';
import { RouterTestingModule } from '#angular/router/testing';
import { Angulartics2, Angulartics2Module } from 'angulartics2';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule,
Angulartics2Module.forRoot(),
HttpClientTestingModule,
],
declarations: [
AppComponent,
HeaderComponent,
],
providers: [
Angulartics2,
],
}).compileComponents();
}));
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
});
});
and for any other component.spec.ts files that you have using the Angulatics2 directives.