Error FormBuilder is not a NgModule when build - json

when i try to start my angular app in local i have th error "Error FormBuilder is not a NgModule", i've tried everything i can do, npm install, check my package json, all things that can resolved my problem, Can you help me please or do you have any solution?
This is my component :
import { Component } from '#angular/core';
import { FormGroup, Validators, NgForm, FormBuilder } from '#angular/forms';
import { Router } from '#angular/router';
import { AuthentificationService } from './authentification.service';
#Component({
selector: 'app-authentification',
templateUrl: './authentification.component.html',
styleUrls: ['./authentification.component.css']
})
export class AuthentificationComponent {
loginForm: FormGroup;
error: string = '';
constructor(
private formBuilder: FormBuilder,
private authentificationService: AuthentificationService,
private router: Router
) {
this.loginForm = formBuilder.group({
'oxylaneId': ['', Validators.required],
'password': ['', Validators.required]
});
}
onSubmit() {
this.authentificationService
.authenticate(this.loginForm.value)
.subscribe(
data => {
localStorage.setItem('id_token', data.token);
this.router.navigate(['email']);
},
error => this.error = error.message
);
}
loginUser(form: NgForm) {
console.log(form.value);
}
onChange(deviceValue) {
console.log(deviceValue);
}
}
And my app.module with all my module and component
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { FormsModule, FormBuilder, FormGroup, Validators } from '#angular/forms';
import { EmailcomponentComponent } from './emailcomponent/emailcomponent.component';
import { ColorcomponentComponent } from './colorcomponent/colorcomponent.component';
import { DesigncomponentComponent } from './designcomponent/designcomponent.component';
import { AppRoutingModule } from './app-routing.module';
import { TopBarComponent } from './top-bar/top-bar.component';
import { AuthentificationComponent } from './authentification/authentification.component';
#NgModule({
imports: [
BrowserModule,
FormsModule,
AppRoutingModule,
FormBuilder,
FormGroup,
Validators,
],
declarations: [
AppComponent,
EmailcomponentComponent,
ColorcomponentComponent,
DesigncomponentComponent,
TopBarComponent,
AuthentificationComponent,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

as the error says: "FormBulder is not a NgModule" and it's not! You should neither import FormBuilder nor FormGroup in imports. Validators also do not belong in Imports unless it's a Feature Module of yours. Import FormsModule or ReactiveFormsModule instead, for example:
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule
AppRoutingModule
]
EDIT:
As best practice, never import FormsModule and ReactiveFormsModule, either one or another!

Related

Cannot use one of my element declared in my own library

I am trying to make a library that I can use a component from but angular says that the element I use is not recognized as an element. I am trying to export the VitalSignLinesListComponent.
The steps I follow are:
declare the component in the library module
export the component
in the library module
export the component in the public API
import the module from the library
place the element in the html
file
receive error
The error I am getting:
ERROR in src/app/app.component.html:2:1 - error NG8001:
'lib-vital-sign-lines-list' is not a known element: 1. If
'lib-vital-sign-lines-list' is an Angular component, then verify that
it is part of this module.
2. If 'lib-vital-sign-lines-list' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '#NgModule.schemas' of this component
to suppress this message.
COMPONENT:
#Component({
selector: 'lib-vital-sign-lines-list',
templateUrl: './vital-sign-lines-list.component.html',
styleUrls: ['./vital-sign-lines-list.component.css']
})
export class VitalSignLinesListComponent implements OnInit {
#Input()
idEdDossier: string;
}
LIBRARY MODULE:
import { NgModule } from '#angular/core';
import { VitalsignsComponent } from './vitalsigns.component';
import { BrowserModule } from '#angular/platform-browser';
import { HttpClientModule } from '#angular/common/http';
import { RouterModule, Routes } from '#angular/router';
import { ModalInputComponent } from './modal-input/modal-input.component';
import { VitalSignLinesListComponent } from './vital-sign-lines-list/vital-sign-lines-list.component';
import { NgSelectModule } from '#ng-select/ng-select';
import { FormsModule } from '#angular/forms';
import { EcareLibModule } from 'ecarelib'
import { NgbModule } from '#ng-bootstrap/ng-bootstrap';
import { ComboBoxComponent } from './combo-box/combo-box.component';
import { ComboBoxPipe } from './combo-box/combo-box.pipe';
import { LogService } from './services/log.service';
import { ClickOutsideDirective } from './vital-sign-lines-list/click-outside.directive';
const appRoutes: Routes = [
{ path: 'modal', component: ModalInputComponent },
{ path: 'vitalSignLinesList', component: VitalSignLinesListComponent }
];
// #dynamic
#NgModule({
declarations: [
VitalsignsComponent,
ModalInputComponent,
VitalSignLinesListComponent,
ComboBoxComponent,
ComboBoxPipe,
ClickOutsideDirective
],
imports: [
BrowserModule,
HttpClientModule,
EcareLibModule.forRoot(),
NgSelectModule,
RouterModule.forRoot(appRoutes, { enableTracing: false }),
FormsModule,
NgbModule
],
providers: [LogService],
exports: [VitalsignsComponent, VitalSignLinesListComponent]
})
export class VitalsignsModule {
}
PUBLIC-API:
export * from './lib/vitalsigns.service';
export * from './lib/vitalsigns.component';
export * from './lib/vitalsigns.module';
export * from './lib/vital-sign-lines-list/vital-sign-lines-list.component';
IMPORT LIBRARY: (VitalsignsModule)
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { NgSelectModule } from '#ng-select/ng-select';
import { FormsModule } from '#angular/forms';
import {NgbModule} from '#ng-bootstrap/ng-bootstrap';
import { AppComponent } from './app.component';
import { HttpClientModule } from '#angular/common/http';
import { RouterModule, Routes } from '#angular/router';
import { EcareLibModule } from 'ecarelib';
import { VitalsignsModule } from 'vitalsigns';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
EcareLibModule.forRoot(),
HttpClientModule,
RouterModule.forRoot([]),
VitalsignsModule,
NgbModule,
NgSelectModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
HTML:
<lib-vital-sign-lines-list [idEdDossier]=idDossier></lib-vital-sign-lines-list>

router navigation not working after login success

angular router not working after login success.
I have Auth Module
Under Auth module i have login components
I have Admin Module
Under Admin module i have 3 components
1).admin component
2).admin-dashboard
3).blog component
In admin.component.html
written (router-outlet) tag.
//getting login success and userdata
{"result":"success","UserId":"U-001","UserName":"Super Admin","UserEmail":"admin#dw.com"}
if result is success trying redirecting to admin component. but it is not working.
please check the code.where i did the mistake?.
Thanks in advance.
app.routing.module.ts
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
//import { PreloadAllModules } from '#angular/router';
import { CustomPreloadingStrategyService } from './custom-preloading-strategy.service';
import { CustomPreloadingWithDealyStrategyService } from './custom-preloading-with-delay-strategy.service';
const routes: Routes = [
{
path:'',redirectTo:'/login',pathMatch:'full'
},
{
path:'**',component:PageNotFoundComponent
}
];
#NgModule({
imports: [RouterModule.forRoot(routes,
{
preloadingStrategy:CustomPreloadingWithDealyStrategyService
})],
providers: [CustomPreloadingStrategyService,CustomPreloadingWithDealyStrategyService],
exports: [RouterModule]
})
export class AppRoutingModule { }
app.module.ts
import { BrowserModule, Title } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AlertModule } from 'ngx-bootstrap';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
import { DragDropModule } from '#angular/cdk/drag-drop';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { HttpClientModule } from '#angular/common/http';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
import { MatToolbarModule, MatFormFieldModule, MatDatepickerModule, MatNativeDateModule, MatInputModule } from '#angular/material';
import { HeaderComponent } from './header/header.component';
import { AuthService } from './auth/auth.service';
import { AdminModule } from './admin/admin.module';
import { AuthModule } from './auth/auth.module';
import { httpInterceptorProviders } from './http-interceptors/index';
#NgModule({
declarations: [
AppComponent,
PageNotFoundComponent, HeaderComponent ],
imports: [
BrowserModule,
DragDropModule,
FormsModule,
ReactiveFormsModule,
AlertModule.forRoot(),
BrowserAnimationsModule,
HttpClientModule,
MatToolbarModule,
MatFormFieldModule,
MatInputModule,
MatDatepickerModule,
MatNativeDateModule,
AdminModule,
AuthModule,
AppRoutingModule],
exports: [MatToolbarModule, MatFormFieldModule, MatInputModule, MatDatepickerModule, MatNativeDateModule,AdminModule,AuthModule],
providers: [Title, AuthService,httpInterceptorProviders],
bootstrap: [AppComponent]
})
export class AppModule {
constructor ()
{
console.log('App Module load');
}
}
admin.routing.module.ts
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { AdminComponent } from './admin/admin.component';
import { AdminDashboardComponent } from './admin-dashboard/admin-dashboard.component';
import { BlogsComponent } from './blogs/blogs.component';
import { AuthGuard } from '../auth/auth.guard';
const routes: Routes = [
{
path: 'admin',
component: AdminComponent,
canActivate: [AuthGuard],
children: [
{
path: '',
children: [
{ path: 'blogs', component: BlogsComponent },
{ path: '', component: AdminDashboardComponent }
],
}
]
}
];
#NgModule({
imports: [RouterModule.forChild(routes)],
providers: [],
exports: [RouterModule]
})
export class AdminRoutingModule { }
admin.module.ts
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { ReactiveFormsModule } from '#angular/forms';
import { AdminRoutingModule } from './admin-routing.module';
import { AdminComponent } from './admin/admin.component';
import { AdminDashboardComponent } from './admin-dashboard/admin-dashboard.component';
import { BlogsComponent } from './blogs/blogs.component';
#NgModule({
declarations: [AdminComponent, AdminDashboardComponent, BlogsComponent],
imports: [
CommonModule,ReactiveFormsModule,AdminRoutingModule
]
})
export class AdminModule { }
login.component.ts
import { Component, OnInit } from '#angular/core';
import { Route, Router } from '#angular/router';
import { FormGroup, FormBuilder, Validators } from '#angular/forms';
import { AuthService } from '../auth.service';
import { Loginuser } from './loginuser';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
submitted = false;
LoginForm:FormGroup;
SuccessAlert : string;
WarningAlert : string;
showSuccessAlert = false;
showWarningAlert = false;
isLoggedIn : boolean
constructor(private router:Router,private fb: FormBuilder, private authservice: AuthService)
{
this.LoginForm = fb.group({
emailid: ['', Validators.compose([Validators.required])],
password: ['', Validators.compose([Validators.required, Validators.minLength(8), Validators.maxLength(8)])],
})
}
ngOnInit() {
this.authservice.logout();
}
LogInUser(){
let login = this.LoginForm.value;
this.checklogin(login);
}
checklogin(loginUser: Loginuser){
this.authservice.userlogin(loginUser).subscribe(
data =>{
if(data["result"]=="success"){
this.showSuccessAlert = true;
this.SuccessAlert = data["result"];
this.LoginForm.reset();
localStorage.setItem("currentUser", JSON.stringify(data));
this.isLoggedIn = true;
this.router.navigate(['/admin']);
}
else
{
this.showWarningAlert = true;
this.WarningAlert = data["result"];
}
}
)
}
}
auth.guard.ts
import { Injectable } from '#angular/core';
import { CanActivate, CanActivateChild, CanLoad, Route, UrlSegment, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '#angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
#Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate, CanActivateChild {
constructor(private router: Router, private authservice: AuthService){}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean | UrlTree {
if(this.authservice.isLoggedIn) {
return true
}
else
{
return false
this.router.navigate(['/login']);
}
}
canActivateChild(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.canActivate(next, state);
}
}
The problem is the router.navigate that does not redirect.
Test the following codes to resolve your issue:
this.router.navigate(["../admin"]);
or
this.router.navigateByUrl('/admin');
this is worked for me.
import { Location } from '#angular/common';
import { Router } from '#angular/router';
this.location.replaceState('/');
this.router.navigate(['home']);
this.location.replaceState
for replace history instead of pushing so if the user goes back it won’t go back to the url that the user was on, but the one before.
router.navigate will not work directly because queryParams is Observable, so you cannot get parameters from it in this way.
Try this
this.router.navigate['../admin']

Module has no exported member 'http' [2305]

Hello I am trying to import http call from '#angular/common/http' and am getting error message that module has no exported member 'http'
Error:[ts] Module '"e:/car/node_modules/#angular/common/http"' has no exported member 'Http'. [2305]
import {
RouterModule
} from '#angular/router';
import {
BrowserModule
} from '#angular/platform-browser';
import {
NgModule
} from '#angular/core';
import {
AppRoutingModule
} from './app-routing.module';
import {
AppComponent
} from './app.component';
import {
HomeComponent
} from './home/home.component';
import {
HttpClientModule
} from '#angular/common/http';
#NgModule({
declarations: [
AppComponent,
HomeComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
RouterModule.forRoot([{
path: '',
component: HomeComponent
}])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
import {
Http
} from '#angular/common/http';
import {
Component,
OnInit
} from '#angular/core';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor(private http: Http) {}
products = [];
fetchData = function() {
this.http.get('http://localhost:5555/products').subscribe(
(res: Response) => {
this.products = res.json();
}
);
};
ngOnInit() {
this.fetchData();
}
}
the below code is used for inserting json file which includes the details
HttpClientModule will inject HttpClient service not the Http.
Please use HttpClient in constructor injection in the HomeComponent.
constructor(private http: HttpClient) {}
For Reference created sample stackblitz code.

Custom directive is not working for angular 6:

Changing backgound color of the paragraph tag using custom directive not working for angular 6 .
#CustomDirective
import { Directive,ElementRef,HostListener } from '#angular/core';
#Directive({
selector: '[appSteps]'
})
export class StepsDirective {
constructor(private elementref: ElementRef){ }
#HostListener('mouseenter')onmouseenter()
{
this.elementref.nativeElement.style.backgroundColor = 'yellow';
}
#HostListener('mouseleave')onmouseleave()
{
this.elementref.nativeElement.style.backgroundColor = 'null';
}
}
#ModuleCreated : Added my directive here and using this module in appmodule.ts
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import {StepsDirective} from '../steps.directive';
#NgModule({
imports: [
CommonModule
],
declarations: [StepsDirective]
})
export class StartModule { }
#AppComponent.html-Hosting my custom directive ontag
<p appSteps>My Hero Academia</p>
#app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { Signup_Component } from './signup/signup.component';
import { FormsModule } from '#angular/forms';
import { HttpClientModule } from '#angular/common/http';
import { StartModule } from './start/start.module'; *Module created
#NgModule({
declarations: [
AppComponent,
Signup_Component,
],
imports: [
BrowserModule,
FormsModule,
HttpClientModule,
StartModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
you should first export the module that you declare your directive in then import it any where you want to use
#NgModule({
imports: [
CommonModule
],
exports:[StepsDirective]
declarations: [StepsDirective]
})
export class StartModule { }

Angular 6 component not showing up

I just started learning Angular yesterday so I apologize if I'm missing something obvious, but I am trying to display a component on the app.component.html, however, it is not showing up.
TS file for the component I am trying to display:
import { Component, OnInit } from '#angular/core';
import { ImageService } from '../shared/image.service';
#Component({
selector: 'image-list',
templateUrl: './image-list.component.html',
styleUrls: ['./image-list.component.css']
})
export class ImageListComponent implements OnInit {
images: any[];
constructor(private _imageService : ImageService ) { }
searchImages(query : string)
{
return this._imageService.getImage(query).subscribe
(
data => console.log(data),
error => console.log(error),
() => console.log("Request Completed!")
);
}
ngOnInit() {
}
}
image-list.component.html :
<button>Find Images</button>
app.component.html :
<image-list></image-list>
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
image.service.ts
import { Injectable } from "#angular/core";
import { environment } from "../../environments/environment";
import { Http, Headers } from "#angular/http";
import { map, filter, scan } from 'rxjs/operators';
#Injectable()
export class ImageService
{
private query: string;
private API_KEY: string = environment.API_KEY;
private API_URL: string = environment.API_URL;
private URL: string = this.API_URL + this.API_KEY + '&q=';
constructor(private _http: Http) {
}
getImage(query)
{
return this._http.get(this.URL + this.query).pipe(
map((res) => res.json));
}
}
I had a similar problem trying to use a component outside its module.
In this case, you have to export a component from your .module.ts:
#NgModule({
// …
declarations: [ MyComponent ],
exports: [ MyComponent ],
// …
})
You need to import your Component and your Service into your app.module.ts and then to declarations and to providers property
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { ImageListComponent } from './image-list.component';
import { ImageService } from './image.service';
#NgModule({
declarations: [
AppComponent,
ImageListComponent
],
imports: [
BrowserModule
],
providers: [ ImageService ],
bootstrap: [AppComponent]
})
export class AppModule { }
Adjust ImageListComponent path into the import statement.
Teorically when you generate a component with Angular CLI with a command like this:
ng generate component image-list
it should update your app.module.ts file for you.
To generate a service use
ng generate service image
check this one
in src/app/app.module.ts
#NgModule({
declarations: [AppComponent],
imports: [BrowserModule, FormsModule, HttpClientModule],
bootstrap: [AppComponent],
})
export class AppModule {}
from this link: https://malcoded.com/posts/why-angular-not-works/
You may try the Angular tutorial from: https://angular.io/start . It shows how to render a custom Ansible component on the app.component.html page.
You just need to update the app.module.ts file. Assuming your component is named ImageListComponent:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { RouterModule } from '#angular/router'; // add this line
import { AppComponent } from './app.component';
import { ImageListComponent } from './image-list/image-list.component'; // add this line
#NgModule({
declarations: [
AppComponent,
ImageListComponent // add this line
],
imports: [
BrowserModule,
// add the following 3 lines
RouterModule.forRoot([
{ path: '', component: ImageListComponent },
])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
First try this, without adding any custom services.
It seems you have nothing that triggers the API call on your method searchImages in ImageComponent. Having a click eventListener on the <button>Find Images</button> tag should do the trick. Also register the ImageComponent and ImageService in your app.module.ts file.