Uncaught ReferenceError: Cannot access 'MaterialModule' before initialization - html

I am working on a simple form for a personal project and try to put a phone form use this example: https://material.angular,.io/components/form-field/examples and after that fits everything it gives me this error and although Remove everything related to the phone form remains the same.
form.component.ts
import { Component, OnInit } from '#angular/core';
import { Builder } from 'protractor';
import {FocusMonitor} from '#angular/cdk/a11y';
import {coerceBooleanProperty} from '#angular/cdk/coercion';
import {ElementRef, Input, OnDestroy, Optional, Self} from '#angular/core';
import {FormBuilder, FormGroup, ControlValueAccessor, NgControl} from '#angular/forms';
import {MatFormFieldControl} from '#angular/material';
import {Subject} from 'rxjs';
#Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.scss'],
providers: [{provide: MatFormFieldControl, useExisting: MyTelInput}],
host: {
'[class.example-floating]': 'shouldLabelFloat',
'[id]': 'id',
'[attr.aria-describedby]': 'describedBy',
}
})
export class MyTelInput implements ControlValueAccessor, MatFormFieldControl<MyTel>, OnDestroy {
static nextId = 0;
parts: FormGroup;
stateChanges = new Subject<void>();
focused = false;
errorState = false;
controlType = 'example-tel-input';
id = `example-tel-input-${MyTelInput.nextId++}`;
describedBy = '';
onChange = (_: any) => {};
onTouched = () => {};
get empty() {
const {value: {area, exchange, subscriber}} = this.parts;
return !area && !exchange && !subscriber;
}
get shouldLabelFloat() { return this.focused || !this.empty; }
#Input()
get placeholder(): string { return this._placeholder; }
set placeholder(value: string) {
this._placeholder = value;
this.stateChanges.next();
}
private _placeholder: string;
#Input()
get required(): boolean { return this._required; }
set required(value: boolean) {
this._required = coerceBooleanProperty(value);
this.stateChanges.next();
}
private _required = false;
#Input()
get disabled(): boolean { return this._disabled; }
set disabled(value: boolean) {
this._disabled = coerceBooleanProperty(value);
this._disabled ? this.parts.disable() : this.parts.enable();
this.stateChanges.next();
}
private _disabled = false;
#Input()
get value(): MyTel | null {
const {value: {area, exchange, subscriber}} = this.parts;
if (area.length === 3 && exchange.length === 3 && subscriber.length === 4) {
return new MyTel(area, exchange, subscriber);
}
return null;
}
set value(tel: MyTel | null) {
const {area, exchange, subscriber} = tel || new MyTel('', '', '');
this.parts.setValue({area, exchange, subscriber});
this.stateChanges.next();
}
constructor(
formBuilder: FormBuilder,
private _focusMonitor: FocusMonitor,
private _elementRef: ElementRef<HTMLElement>,
#Optional() #Self() public ngControl: NgControl) {
this.parts = formBuilder.group({
area: '',
exchange: '',
subscriber: '',
});
_focusMonitor.monitor(_elementRef, true).subscribe(origin => {
if (this.focused && !origin) {
this.onTouched();
}
this.focused = !!origin;
this.stateChanges.next();
});
if (this.ngControl != null) {
this.ngControl.valueAccessor = this;
}
}
ngOnDestroy() {
this.stateChanges.complete();
this._focusMonitor.stopMonitoring(this._elementRef);
}
setDescribedByIds(ids: string[]) {
this.describedBy = ids.join(' ');
}
onContainerClick(event: MouseEvent) {
if ((event.target as Element).tagName.toLowerCase() != 'input') {
this._elementRef.nativeElement.querySelector('input')!.focus();
}
}
writeValue(tel: MyTel | null): void {
this.value = tel;
}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
}
_handleInput(): void {
this.onChange(this.parts.value);
}
}
export class MyTel {
constructor(public area: string, public exchange: string, public subscriber: string) {}
}
export class FormComponent implements OnInit {
public formGroup: FormGroup;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.formGroup = this.formBuilder.group({
name: '',
lastname: '',
option: '',
checkbox: '',
masculino: '',
femenino: '',
email:'',
});
}
}
form.module.ts
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { FormRoutingModule } from './form-routing.module';
import { FormComponent } from './form/form.component';
import { MaterialModule } from '../material/material.module';
import { FormBuilder } from '#angular/forms';
#NgModule({
declarations: [FormComponent],
imports: [
CommonModule,
FormRoutingModule,
MaterialModule
],
providers: [
FormBuilder
]
})
export class FormModule { }
material.module.ts
import { NgModule } from '#angular/core';
import {
MatTableModule,
MatPaginatorModule,
MatFormFieldModule,
MatSelectModule,
MatInputModule,
MatCheckboxModule,
MatRadioModule} from '#angular/material';
import { ReactiveFormsModule } from '#angular/forms';
import { FormModule } from '../form/form.module';
import { FormComponent } from '../form/form/form.component';
const materialModules = [
MatTableModule,
MatPaginatorModule,
MatFormFieldModule,
ReactiveFormsModule,
MatSelectModule,
MatInputModule,
MatRadioModule,
FormModule,
FormComponent,
MatCheckboxModule,
];
#NgModule({
exports: materialModules,
imports: materialModules
})
export class MaterialModule { }
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NoopAnimationsModule } from '#angular/platform-browser/animations';
import { MaterialModule } from './modules/material/material.module';
import { MatSelectModule, MatInputModule, MatCheckbox, MatRadioModule } from '#angular/material';
import { MatFormFieldModule } from '#angular/material/form-field';
import { FormModule } from './modules/form/form.module';
import { FormComponent } from './modules/form/form/form.component';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
NoopAnimationsModule,
MaterialModule,
MatSelectModule,
MatInputModule,
MatFormFieldModule,
MatRadioModule,
FormModule,
FormComponent
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
form-routing.component.ts
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { FormComponent } from './form/form.component';
const routes: Routes = [{path: '', component: FormComponent}];
#NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class FormRoutingModule { }
Please help

you have 2 major errors here:
importing a component to a module. Can't be done, only modules can be imported. Components can be declared and exported. This is causing the error you're seeing.
Circular module imports by importing FormModule to MaterialModule and vice versa. Can't do it. Imports can only go in one direction. This is causing the warning you're seeing which is actually an error preventing you from recompiling.
And some minor errors, like you're mixing up module logic and double importing modules
fixes below....
material module, let it do what it's supposed to do, import and export material modules, NOTHING ELSE, remover reactive forms import, remove circular reference to FormsModule, remove form component import:
import { NgModule } from '#angular/core';
import {
MatTableModule,
MatPaginatorModule,
MatFormFieldModule,
MatSelectModule,
MatInputModule,
MatCheckboxModule,
MatRadioModule} from '#angular/material';
const materialModules = [
MatTableModule,
MatPaginatorModule,
MatFormFieldModule,
MatSelectModule,
MatInputModule,
MatRadioModule,
MatCheckboxModule,
];
#NgModule({
exports: materialModules,
imports: materialModules
})
export class MaterialModule { }
form module, import the reactive forms module here (dont provide the form builder), export your forms component to use it in other modules:
#NgModule({
declarations: [FormComponent],
imports: [
CommonModule, // if you have a common module, you could import / export the reactive forms module there if it's more appropriate and then you don't need to import it again here.
FormRoutingModule,
MaterialModule,
ReactiveFormsModule // do this here, don't provide the form builder
],
exports: [
FormComponent // if you want to use this component in other modules, export here and import the MODULE
]
})
export class FormModule { }
app module, don't try to import the form component, just the module. Don't reimport material modules, you do that in the material module:
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
NoopAnimationsModule,
MaterialModule, // do you really NEED the material module here?
FormModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Related

Why does the function run twice in my every component

I have this problem where i made three different components with routing. The problem is when i open my different components they loop twice at the moment i open them. What is causing this and how can i get rid of it?
Heres one example component which console.log runs twice when i open it.
import { Component, OnInit } from '#angular/core';
import nameData from '../../names/names.json'
interface INames {
name: string,
amount: number
}
const { names } = nameData
#Component({
selector: 'app-four',
templateUrl: './four.html',
styleUrls: ["./four.css"]
})
export class FourComponent {
nameArray: Array<INames> = names
constructor() {
}
hasName(nameParam: any) {
console.log("miksi tämä tulee kaksi kertaa")
return this.nameArray.some(elem => elem.name === nameParam)
}
}
And here is the app.module.ts and app-routing.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { OneComponent } from './requirements/one/one';
import { TwoComponent } from './requirements/two/two';
import { ThreeComponent } from './requirements/three/three';
import { FourComponent } from './requirements/four/four';
import { NgbModule } from '#ng-bootstrap/ng-bootstrap';
import { HeaderComponent } from './header/header';
#NgModule({
declarations: [
AppComponent,
OneComponent,
TwoComponent,
ThreeComponent,
FourComponent,
HeaderComponent
],
imports: [
BrowserModule,
AppRoutingModule,
NgbModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app-routing-module.ts
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { HomeComponent } from './home/home';
import { FourComponent } from './requirements/four/four';
import { OneComponent } from './requirements/one/one';
import { ThreeComponent } from './requirements/three/three';
import { TwoComponent } from './requirements/two/two';
const appRoutes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'one', component: OneComponent },
{ path: 'two', component: TwoComponent },
{ path: 'three', component: ThreeComponent },
{ path: 'four', component: FourComponent }
]
#NgModule({
imports: [RouterModule.forRoot(appRoutes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
I'm really confused why it loops the function as soon as i press the components button?
I do not recommand at all to use function in the HTML template, because they will be called everytime the Angular's change detection runs. Angular isn't able to tell if the result of the function will be different after each modification, si Angular will call the function everytime something change in the UI.
You must store the result of the function in a variable. Angular can check that the reference of the variable hasn't change.
You can read more information about it on this medium.
I recommend that you do the following
public fullName: string;
constructor() {
this.updateName();
}
private updateName(nameParam: any) {
console.log("miksi tämä tulee kaksi kertaa");
this.fullName = this.nameArray.some(elem => elem.name === nameParam);
}
{{ fullName }}

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']

#ngrx/store-devtools - effects called twice

All actions I dispatch in effects are called twice. I already figured out, that this is caused by StoreDevtoolsModule. When I kick StoreDevtoolsModuleout of the app.module.ts my action will be called only once => everything is fine.
Here's my setup:
Angular 6.0.1
"#ngrx/effects": "6.0.0-beta.1",
"#ngrx/entity": "5.2.0",
"#ngrx/router-store": "6.0.0-beta.1",
"#ngrx/store": "6.0.0-beta.1",
"#ngrx/store-devtools": "6.0.0-beta.1",
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { StoreModule, Store, combineReducers, ActionReducerMap, MetaReducer }
from '#ngrx/store';
import { StoreDevtoolsModule } from '#ngrx/store-devtools';
import { EffectsModule } from '#ngrx/effects';
import { EquipmentModule } from './modules/equipment/equipment.module';
const reducers: ActionReducerMap<IAppState> = {
equipments: EquipmentReducer
};
#NgModule({
declarations: [
AppComponent
],
imports : [
BrowserModule,
StoreModule.forRoot(reducers),
StoreDevtoolsModule.instrument({
name: 'EQUIPMENT',
maxAge: 10,
logOnly: true,
}),
EquipmentModule,
EffectsModule.forRoot([]),
]
})
export class AppModule
{}
equipment.module.ts
import { EffectsModule } from '#ngrx/effects';
import { EquipmentEffects } from './equipment.effect';
import { EquipmentMockService } from './equipment.mock';
#NgModule({
imports: [
EffectsModule.forFeature([EquipmentEffects])
],
providers: [
{
provide: 'IEquipmentService',
useClass: EquipmentMockService
},
]
})
export class EquipmentModule {
}
equipment.effect.ts
import { CustomAction } from './../../custom.action';
import { Injectable, Inject } from '#angular/core';
import { Http } from '#angular/http';
import { Actions, Effect, ofType } from '#ngrx/effects';
import { Observable } from 'rxjs/Observable';
import { catchError, map, mergeMap } from 'rxjs/operators';
import { EquipmentActions } from './equipment.action';
import { HttpClient } from '#angular/common/http';
import { Action, State } from '#ngrx/store';
import { of } from 'rxjs/internal/observable/of';
import { EquipmentService } from './equipment.service';
import { IAppState } from '../../app.state';
import { ofTypeWithPayload } from '../../customActionHelper';
#Injectable()
export class EquipmentEffects {
constructor(
private http: HttpClient,
private actions$: Actions,
private readonly state: State<IAppState>,
#Inject('IEquipmentService')
private equipmentService: EquipmentService
) { }
#Effect()
getAllEquipments$: Observable<Action> = this.actions$.pipe(
ofType(EquipmentActions.LOAD_ALL_EQUIPMENTS),
mergeMap(action => {
console.log('here'); <-- This console.log gets called twice!
return this.equipmentService.getAllEquipments().pipe(
map(equipments => ({ type: 'LOAD_ALL_EQUIPMENTS_SUCCESS', payload: equipments })),
catchError(() => of({ type: 'LOAD_ALL_EQUIPMENTS_FAIL' }))
);
}
)
);
Does anyone have an idea?
Thanks

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.

Error FormBuilder is not a NgModule when build

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!