mat-form-field is invisible - html

I am very new in angular and I tried to write project that have two input field.
and I have a problem that I cant see those field on the website but they are clickable and I can write text in them. it happend to me after I added mat-error to those two field.
Someone know what is my problem.
this is my app.component.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Yooz application</title>
<link rel="stylesheet" href="app.component.css">
</head>
<body>
<!-- website title -->
<h1 class="title">
Welcome to my Website
</h1>
<form [formGroup]="form">
<mat-form-field class="emailFormField">
<mat-label>Email</mat-label>
<input matInput formControlName="email" type="text" name="none">
<mat-error *ngIf="this.form.controls['email'].hasError('required')">
It is required field
</mat-error>
</mat-form-field>
</form>
<form [formGroup]="form">
<mat-form-field class="passwordFormField">
<mat-label>Password</mat-label>
<input matInput formControlName="password" type="text" name="none">
<mat-error *ngIf="this.form.controls['password'].hasError('required')">
It is required field
</mat-error>
</mat-form-field>
</form>
</body>
</html>
this is my app.component.ts:
import { Component } from '#angular/core';
import {
FormBuilder,
FormControl,
FormGroup,
Validator,
Validators,
} from '#angular/forms'
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'yoozProject';
form: FormGroup;
constructor (private fb: FormBuilder) {
this.form = this.fb.group({
name: new FormControl('', [Validators.required]),
lastName: new FormControl('', [Validators.required]),
});
}
}
and this is my app.module.ts:
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent} from './app.component';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
import {MatInputModule} from '#angular/material/input';
import { MatFormFieldModule } from '#angular/material/form-field';
import { ReactiveFormsModule } from '#angular/forms';
#NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
MatInputModule,
MatFormFieldModule,
ReactiveFormsModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Your DevTools console will probably tell you exactly what is wrong. Open your Angular app, press F12 and check out the console tab.
I think the issue is a mismatch in your form. In the HTML your referencing to 'email' and 'password' while in the formbuilder you're using 'name' and 'lastName'.

Related

Mat error is not working in the Angular following code?

I want to know why Mat error is not working in the Angular following code?
<div class="form-group">
<mat-form-field class="row-styling">
<mat-label for="aplctnName">
Application Name <span class="text-danger font-weight-bold">*</span>
</mat-label>
<input
matInput
type="text"
placeholder="Enter Application Name here"
alphabetOnly
maxlength="40"
formControlName="aplctnName"
[ngClass]="{ 'is-invalid': submitted && fields.aplctnName.errors }"
/>
<mat-error *ngIf="fields.aplctnName.errors.required"
>Application Name is required</mat-error
>
error>
</mat-form-field>
</div>
In the following code, mat-error is not working whenever I am pressing the next button.
can anyone please help in resolving this issue ?
You can check my solution.
app.module.ts
import { NgModule } from '#angular/core';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { MatFormFieldModule } from '#angular/material/form-field';
import { MatInputModule } from '#angular/material/input';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
#NgModule({
imports: [ BrowserModule, FormsModule, ReactiveFormsModule, MatFormFieldModule, MatInputModule, BrowserAnimationsModule ],
declarations: [ AppComponent, HelloComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
styles.scss
/* Add application styles & imports to this file! */
#import "#angular/material/prebuilt-themes/deeppurple-amber.css";
app.component.ts
import { Component, VERSION, OnInit } from '#angular/core';
import { FormGroup, FormControl, Validators } from '#angular/forms';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
form: FormGroup;
submitted: boolean = false;
ngOnInit() {
this.form = new FormGroup({
aplctnName: new FormControl('', Validators.required)
});
console.log(this.form)
}
onSubmit(event) {
}
}
app.component.html
<form [formGroup]="form" (ngSubmit)="onSubmit($event)">
<div class="form-group">
<mat-form-field class="row-styling">
<mat-label for="aplctnName">
Application Name <span class="text-danger font-weight-bold">*</span>
</mat-label>
<input
matInput
type="text"
placeholder="Enter Application Name here"
alphabetOnly
maxlength="40"
formControlName="aplctnName"
[ngClass]="{ 'is-invalid': submitted && form.get('aplctnName').errors }"
/>
<mat-error *ngIf="form.get('aplctnName').errors?.required"
>Application Name is required</mat-error
>
</mat-form-field>
<button type="submit">submit</button>
</div>
</form>
you can check working demo here
Let me know if you still face any issue.

There is nothing displayed in my Angular App

I'm new in web development and i am following this tutorial, and up til i before back-end code i tried to build it but there is nothing in the page, i tried ng serve and ng build (then served it to my local IIS). here are the codes
index.html (build)
<!doctype html>
<html lang="en">
<head>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<meta charset="utf-8">
<title>NewApp</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
<script src="runtime-es2015.js" type="module"></script><script src="runtime-es5.js" nomodule defer></script><script src="polyfills-es5.js" nomodule defer></script><script src="polyfills-es2015.js" type="module"></script><script src="styles-es2015.js" type="module"></script><script src="styles-es5.js" nomodule defer></script><script src="vendor-es2015.js" type="module"></script><script src="vendor-es5.js" nomodule defer></script><script src="main-es2015.js" type="module"></script><script src="main-es5.js" nomodule defer></script></body>
</html>
app-routing.module.ts
import { NgModule, Component } from "#angular/core";
import { RouterModule,Routes } from '#angular/router';
import {AuthGuard} from './helpers/canActivateAuthGuard';
import { LoginComponent } from './components/login/login.component';
import { LogoutComponent } from './components/login/logout.component';
import { DashboardComponent } from './components/dashboard/dashboard.component';
import { UsersComponent } from './components/users/users.component';
import {AppComponent} from './layout/app.component'
const routes: Routes = [
{path: '', redirectTo: '/dashboard', pathMatch: 'full', canActivate: [AuthGuard]},
{path: 'login', component: LoginComponent},
{path: 'logout', component: LogoutComponent},
{path: 'dashboard', component: DashboardComponent},
{path: 'users', component: UsersComponent},
]
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
app.module.ts
import {MatButtonModule} from '#angular/material/button';
import {MatCheckboxModule} from '#angular/material/checkbox'
import {MatInputModule} from '#angular/material/input';
import {MatFormFieldModule} from '#angular/material/form-field';
import {MatSidenavModule, MatSidenav} from '#angular/material/sidenav';
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
import { AppRoutingModule } from './app-routing.module';
import {HttpClientModule} from '#angular/common/http';
#NgModule({
imports: [
BrowserModule,
BrowserAnimationsModule,
MatButtonModule,
MatCheckboxModule,
MatInputModule,
MatFormFieldModule,
MatSidenavModule,
AppRoutingModule,
HttpClientModule],
})
export class AppModule{}
app.component.html
<div *ngIf="authentication">
<app-head></app-head>
<button type="button" mat-button (click)="drawer.toggle()">
Menu
</button>
<mat-drawer-container class="example-container" autosize>
<mat-drawer #drawer class="example=sidenav" mode="slide">
<app-left-panel></app-left-panel>
</mat-drawer>
<div>
<router-outlet></router-outlet>
</div>
</mat-drawer-container>
</div>
<div *ngIf="!authentication"><app-login></app-login></div>
app.component.ts
import { Component } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'new-app';
}
Your AppComponent is never declared. You are missing the following in the AppModule
#NgModule({
declarations : [AppComponent],
bootstrap: [AppComponent],
imports: [
...
This should have been indicated in your browsers developer tools.
As it was already described here you should add AppComponent to declarations and bootstrap array inside of AppModule
#NgModule({
declarations : [AppComponent],
bootstrap: [AppComponent],
imports: [...]
})
You are also using authentication property inside of *ngIf in app.component.html but this property is not defined inside of app.component.ts
Try to add it to the app.component.ts
import { Component } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'new-app';
authentication = true;
}
This actually didn't cause any error message in console when I tested it on Stackblitz
It's also described in the tutorial you provided
Basically we will have an authentication property in the component
which will allow us to remove the header and the menu if the user is
not logged in, and instead, show a simple login page.

Why is my code for 'mat-form-field' not working?

I'm totaly new to angular, and i was practicing using material and adding form fields. I followed all the guides, downloaded all the packages and my code is just copy-pased from a guide but it's still not displaying on my browser.
My console initialy showed
"Unexpected directive 'MatFormField' imported by the module 'AppModule'. Please add a #NgModule annotation."
and after googling it I was told to replace it with "MatFormFieldModule" but after i did i got this error
"NullInjectorError: StaticInjectorError(AppModule)[CdkObserveContent -> ElementRef]:
StaticInjectorError(Platform: core)[CdkObserveContent -> ElementRef]:
NullInjectorError: No provider for ElementRef!"
My code:
app.component.html
<p>works</p>
<form class = "tp-form">
<mat-form-field class = "tp-full-width">
<input matInput placeholder = "Favorite Food" value = "Pasta">
</mat-form-field>
<mat-form-field class = "tp-full-width">
<textarea matInput placeholder = "Enter your comment"></textarea>
</mat-form-field>
<mat-form-field class = "tp-full-width">
<input matInput placeholder = "Email" [formControl] =
"emailFormControl">
<mat-error *ngIf = "emailFormControl.hasError('email')
&& !emailFormControl.hasError('required')">
Please enter a valid email address
</mat-error>
<mat-error *ngIf = "emailFormControl.hasError('required')">
Email is <strong>required</strong>
</mat-error>
</mat-form-field>
</form>
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 { CourseComponent } from './course/course.component';
import {BrowserAnimationsModule} from '#angular/platform-
browser/animations';
import {MatInputModule, MatFormField, MatFormFieldModule} from
'#angular/material'
import {FormsModule, ReactiveFormsModule} from '#angular/forms';
import { CUSTOM_ELEMENTS_SCHEMA } from '#angular/core';
const modules = [
BrowserAnimationsModule,
MatInputModule,
FormsModule,
ReactiveFormsModule,
MatFormFieldModule
]
#NgModule({
declarations: [
AppComponent,
CourseComponent
],
imports: [
BrowserModule,
AppRoutingModule,
...modules
],
exports:[
...modules
],
providers: [],
bootstrap: [AppComponent]
,
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class AppModule { }
app.component.ts
import { Component } from '#angular/core';
import { FormControl } from "#angular/forms";
import { Validators } from '#angular/forms';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'materialApp';
emailFormControl = new FormControl('', [
Validators.required,
Validators.email,
]);
}
Currently my browser is only showing "works".
emailFormControl should be define with ViewChild annotation, like this:
import { Component, ElementRef, ViewChild } from '#angular/core'
...
#ViewChild('emailFormControl') emailFormControl: ElementRef
In short, ViewChild allows us to query elements (from the docs: https://angular.io/api/core/ViewChild)
In this example we used the query target our emailFormControl an get a valid reference

Angular 4 Component is rendered as empty

I am new to Angular, I am trying to define a component and use it in my main page.
The thing is that when using the component in index.html all I can see is my <custom-component></custom-component> empty, nothing inside it.
So what I did is:
in Angular cli: ng generate component custom.
in custom.component.html I have just a text inside paragraph tag.
in index.html I inserted the selector found in custom.component.ts (app-custom) as tag.
in app.module.ts I imported the custom component.
ng serve outputs only app-custom tag without the paragraph tag that should be inside it.
What did I miss?
Update:
Code of my component:
custom.component.html
<p>
component works!
</p>
custom.component.ts
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-custom',
templateUrl: './custom.component.html',
styleUrls: ['./custom.component.css']
})
export class CustomComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>TestApp</title>
<base href="/">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-custom></app-custom>
</body>
</html>
app.module.ts:
import { CustomComponent } from './custom/custom.component';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { FlexLayoutModule } from '#angular/flex-layout';
import { AppComponent } from './app.component';
#NgModule({
declarations: [
AppComponent,
CustomComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
BrowserAnimationsModule,
FlexLayoutModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Try to add exports after declarations => [AppComponent, CustomComponent] ? in app.module. Or create a new cli project with the last version
In NgModule.bootstrap, add your own component.
#NgModule({
declarations: [
AppComponent,
CustomComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [
AppComponent,
CustomComponent
]
})
export class AppModule { }
Try this in index.html add the Appcomponent selector tag and inside Appcomponent template refer your custom component selector and don't forgot to import and declare the custom component in app module and bootstrap the Appcomponent so it renders the app component on load which internally refers your custom component. There are many tutorials outside just start with a single component if you are using AngularCli everything is made easy for you.

Route navigation in Angular4 not reacting

I have made an Angular4 component and the page that it generates has a button to navigate to another page. I don't get any errors and the pageUrl changes but the content of the page stays the same.
Here is my code:
app.component.ts
import { Component } from '#angular/core';
import { Router } from "#angular/router";
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private router: Router){}
username = "";
password = "";
log = function () {
if (this.username != "" && this.password != "") {
console.log(this.username + " " + this.password);
this.router.navigate(['/dashboard']);
}
}
}
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { RouterModule } from '#angular/router';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { AppComponent } from './app.component';
import { DashboardComponent } from './dashboard/dashboard.component';
#NgModule({
declarations: [
AppComponent,
DashboardComponent,
],
imports: [
BrowserModule,
FormsModule,
RouterModule.forRoot([
{
path: 'dashboard',
component: DashboardComponent
}
]
)
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {
}
app.component.html
<div class="outer-container">
<div class="inner-container">
<div class="centered-content">
<div class="center"><img src="../favicon.png"></div>
<label class="addText"> Username: </label><input [(ngModel)]
="username" class="addText"><br>
<label class="addText"> Password: </label><input [(ngModel)]
="password" type="password" class="addText"><br>
<div class="center"><button (click) ="log()">Log in</button></div>
</div>
</div>
</div>
To achieve what you want, have the app.component only to include the router-outlet:
#Component({
selector: 'app-root',
template: `
<!-- Views go here-->
<router-outlet></router-outlet>
`,
})
export class AppComponent { }
And then have a separate component for each view you want. So in your case you'd want to create a LoginComponent, which would then route to the DashboardComponent from there.
PS Of course this is expandable and you could add a header component tag in the AppComponent html, or whatever else and so on and so on. But just to showcase this simple use case.
you need to specify where to display the DashboardComponent
add this tag to tell angular the location where to display the component results from router
<router-outlet></router-outlet>