Angular 6 file upload with other form data - angular6

I have enter data user details first_name,last_name,phone_number and profile_pic but file is not upload in other form data how can i upload file with other form data??
user-form.component.ts
import { Component, OnInit } from '#angular/core';
import { FormGroup, FormBuilder, Validators } from '#angular/forms';
import { Router } from '#angular/router';
import { HttpClient } from '#angular/common/http';
import { UserService } from '../user.service';
import { FileUploader, FileSelectDirective } from 'ng2-file-upload/ng2-file-upload';
#Component({
selector: 'user-form',
templateUrl: './user-form.component.html',
styleUrls: ['./user-form.component.scss']
})
export class UserFormComponent {
angForm: FormGroup
router: Router;
constructor(private userservice: UserService, private fb: FormBuilder, private _route: Router) {
this.createForm();
this.router = _route;
}
createForm() {
this.angForm = this.fb.group({
first_name: ['', Validators.required],
last_name: ['', Validators.required],
// email: ['', Validators.required,Validators.email],
email: ['', Validators.compose([Validators.required, Validators.email])],
phone_number: ['', Validators.compose([Validators.required, Validators.maxLength(10)])],
profile_pic:[]
});
}
addUser(first_name, last_name, email, phone_number,profile_pic) {
var data = {
first_name: first_name,
last_name: last_name,
email: email,
phone_number: phone_number,
profile_pic: profile_pic,
}
console.log(data);
// this.uploader.onAfterAddingFile = (file) => { file.withCredentials = false; }
// public uploader : FileUploader;
// uploader.onAfterAddingFile = (file) => { file.withCredentials = false; }
this.userservice.addUser(data);
this.router.navigate(['/pages/users/list']); //Redirection path
}
}
user-form.component.html
<div class="row justify-content-center">
<div class="col-lg-8">
<nb-card>
<nb-card-header>Add User</nb-card-header>
<nb-card-body>
<!-- <div [formGroup]="form"> -->
<form [formGroup]="angForm" novalidate>
<div class="row full-name-inputs form-group">
<div class="col-sm-6 input-group">
<input type="text" placeholder="First Name" formControlName="first_name" class="form-control" #firstName/>
</div>
<div *ngIf="angForm.controls['first_name'].invalid && (angForm.controls['first_name'].dirty || angForm.controls['first_name'].touched)" class="alert alert-danger" >
<div *ngIf="angForm.controls['first_name'].errors.required">
First Name is required.
</div>
</div>
<div class="col-sm-6 input-group">
<input type="text" placeholder="Last Name" formControlName="last_name" class="form-control" #lastName/>
</div>
<div *ngIf="angForm.controls['last_name'].invalid && (angForm.controls['last_name'].dirty || angForm.controls['last_name'].touched)" class="alert alert-danger" >
<div *ngIf="angForm.controls['last_name'].errors.required">
Last Name is required.
</div>
</div>
</div>
<div class="form-group input-group">
<input type="email" placeholder="Email" formControlName="email" class="form-control" #email/>
</div>
<div *ngIf="angForm.controls['email'].invalid && (angForm.controls['email'].dirty || angForm.controls['email'].touched)" class="alert alert-danger" >
<div *ngIf="angForm.controls['email'].errors.required">
Email is required.
</div>
<div *ngIf="angForm.controls['email'].errors.email">
Enter valid email.
</div>
</div>
<div class="form-group input-group">
<input type="number" placeholder="Phone Number" formControlName="phone_number" class="form-control" #phoneNumber/>
</div>
<div *ngIf="angForm.controls['phone_number'].invalid && (angForm.controls['phone_number'].dirty || angForm.controls['phone_number'].touched)" class="alert alert-danger" >
<div *ngIf="angForm.controls['phone_number'].errors.required">
Phone Number is required.
</div>
<div *ngIf="angForm.controls['phone_number'].errors.maxLength">
Phone Number must be 10 digits
</div>
</div>
<div class="form-group input-group">
<input type="file" class="form-control file-data" formControlName="profile_pic" #profilePic />
</div>
<div class="input-group">
<!-- <input type="submit" class="btn btn-success btn-rectangle btn-demo ml-auto submit-btn" name="Submit" > -->
<button (click)="addUser(firstName.value, lastName.value,email.value,phoneNumber.value,profilePic.value);" [disabled]="angForm.pristine || angForm.invalid" class="btn btn-success btn-rectangle btn-demo ml-auto submit-btn">Submit</button>
</div>
</form>
<!-- </div> -->
</nb-card-body>
</nb-card>
</div>
</div>
When using form-data to upload file with other form inputs
string and file upload to REST API by form-data. Can anyone please suggests for this? Thanks in advance.

try below code to post data with file upload.
ngOnInit() {
this.uploader.onBuildItemForm = (fileItem: any, form: any) => {
form.append('appNo', this.appNo); //note comma separating key and value
};
}

Related

how to use checkbox in reactive angular form

I am new to angular, currently I am looking checkboxes in angular , I have three checkboxes and I have to show checked or unchecked checkboxes in UI.
I am getting enabled/disabled from json , I need to show if am getting enabled means checkbox should be checked and disabled means unchecked checkbox.
This is what am trying in html
<form [formGroup]="portFilterGroup">
<div class="form-group row">
<div class="col-md-4 text-left" id="email">
<label for="email"><input type="checkbox" (change)="onChecked($event)" formcontrolName="emailData" value="{{emailData}}" [checked]="isChecked" >
<b>Email(POP3, IMAP, SMTP)</b></label>
</div>
</div>
<div class="form-group row">
<div class="col-md-4 text-left" id="ftp">
<label for="ftp"><input type="checkbox" formcontrolName="ftpData" [checked]="isChecked" value="{{ftpData}}"> <b>FTP</b></label>
</div>
</div>
<div class="form-group row">
<div class="col-md-4 text-left" id="http">
<label for="http"><input type="checkbox" formcontrolName="httpData"
[checked]="isChecked"> <b>HTTP</b></label>
</div>
</div>
</form>
typescript file
portFilterForm(){
this.portFilterGroup = this.fb.group({
emailData: new FormControl(''),
ftpData: new FormControl(''),
httpData: new FormControl('')
})
}
onChecked(e){
console.log("e", e.target)
if (e.target == 'enabled'){
this.isChecked = true;
}
else{
this.isChecked = false;
}
}
gettingData(){
this.httpClient.get("assets/json/data.json").subscribe((data:any) =>{
console.log(data);
this.emailData = this.onChecked(data.email)
this.httpData = this.onChecked(data.http)
})
}
and the json file be
{
"email": "enabled",
"ftp": "disabled",
"http": "enabled"
}
this is the code am trying, but am not get the expecting output(enabled means checked and disabled means unchecked) can anyone help me to this?
Ok so you can use the angular way read here
html
<form [formGroup]="portFilterGroup">
<div class="form-group row">
<div class="col-md-4 text-left" id="email">
<label
><input
type="checkbox"
[formControl]="portFilterGroup.controls['emailData']"
/> <b>Email(POP3, IMAP, SMTP)</b></label
>
</div>
</div>
<div class="form-group row">
<div class="col-md-4 text-left" id="ftp">
<label
><input
type="checkbox"
[formControl]="portFilterGroup.controls['ftpData']"
/> <b>FTP</b></label
>
</div>
</div>
<div class="form-group row">
<div class="col-md-4 text-left" id="http">
<label
><input
type="checkbox"
[formControl]="portFilterGroup.controls['ftpData']"
/> <b>HTTP</b></label
>
</div>
</div>
</form>
{{ portFilterGroup.value | json }}
<button (click)="gettingData()">submit</button>
ts file
import { Component } from '#angular/core';
import { FormControl, FormGroup, FormBuilder, FormArray } from '#angular/forms';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
name = 'Angular 6';
portFilterGroup: FormGroup;
constructor(private fb: FormBuilder) {
this.portFilterForm();
}
portFilterForm() {
this.portFilterGroup = this.fb.group({
emailData: new FormControl(false),
ftpData: new FormControl(false),
httpData: new FormControl(false),
});
}
gettingData() {
console.log(this.portFilterGroup.value);
// this.httpClient.get('assets/json/data.json').subscribe((data: any) => {
// console.log(data);
// this.emailData = this.onChecked(data.email);
// this.httpData = this.onChecked(data.http);
// });
}
}
stackblitz

How I can access my properties inside the FormGroup? I need to access some properties (touched and errors)

I have this problem:
Property 'institutionName' does not exist on type 'FormGroup'.
*ngIf="frmStepperControl.institutionName.touched && frmStepper.institutionName.errors?.required">
My ts code
import { Component, OnInit } from '#angular/core';
import { FormBuilder, Validators, AbstractControl, FormGroup, FormControl, FormArray} from '#angular/forms'
#Component({
selector: 'app-forms',
templateUrl: './forms.component.html',
styleUrls: ['./forms.component.scss']
})
export class FormsComponent implements OnInit {
frmValues: object = {};
frmStepper: FormGroup;
public get formArray(): AbstractControl {
// console.log(this.frmStepper.get('steps'));
return this.frmStepper.get('steps');
}
public get frmStepperControl(){
console.log(this.frmStepper.get('steps')['controls'].controls.institutionName);
return this.frmStepper.get('steps')['controls'];
}
constructor(private fb: FormBuilder) {
}
ngOnInit(): void {
this.frmStepper = this.fb.group({
steps: this.fb.array([
this.fb.group({
ieCode: [''],
institutionName: ['', Validators.compose([Validators.required])],
}),
this.fb.group({
telephone1: [null],
}),
])
});
}
submit(): void {
console.log(this.frmStepper.value.steps[0].institutionName);
//this.frmValues = this.frmStepper.value;
}
}
My html code where I'm trying access the touched and errors properties from my institutionName property
<form [formGroup]="frmStepper" (ngSubmit)="submit()">
<timeline-stepper #cdkStepper formArrayName="steps" [linear]="true">
<cdk-step [editable]="false" formGroupName="0" [stepControl]="formArray.get([0])" class="form-cdk">
<div class="row">
<p>Instituição de ensino</p>
<div class="horizontal-divider"></div>
<div class="form-group col-md-6">
<label for="ieCode">Código da IE/IF</label>
<input formControlName="ieCode" type="text" class="form-control" id="ieCode" placeholder="Escreva aqui...">
</div>
<div class="form-group col-md-6">
<label for="institutionName">Nome da Instituição*</label>
<input formControlName="institutionName" type="text" class="form-control" id="institutionName"
placeholder="Escreva aqui..."
required>
<span class="text-danger"
*ngIf="frmStepperControl.institutionName.touched && frmStepper.institutionName.errors?.required">
Nome da Instituição é obrigatória
</span>
</div>
</div>
<footer class="row">
<div class="col-md-6"></div>
<div class="form-group col-md-3">
<button type="button" class="btn btn-primary next" cdkStepperNext>PRÓXIMO</button>
</div>
</footer>
</cdk-step>
<cdk-step #contacts [editable]="false" formGroupName="1" [stepControl]="formArray.get([1])">
<div class="row">
<div class="form-group col-md-6">
<label for="telephone1">Telef.1</label>
<input formControlName="telephone1" type="number" class="form-control" id="telephone1" placeholder="Escreva aqui.">
</div>
</div>
<footer class="row lastRow">
<div class="form-group col-md-3">
<button type="submit" class="btn btn-primary next">PRÓXIMO</button>
</div>
</footer>
</cdk-step>
</timeline-stepper>
</form>
Property 'institutionName' does not exist on type 'FormGroup'.
I'm facing this problem.
In you HTML you have frmStepper.InstitutionName.errors
Should be frmStepperControl.InstitutionName.errors

Object is possibly 'null' in typescript/angular

I have been learning angular and typescript for the past couple of days and I've hit an error I can't really fix when calling methods in the *ngIf text field on my member-form.component.html.
The member-component.ts is:
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute, Router } from '#angular/router';
import { MemberService } from '../member.service';
import { Member } from '../member';
import { FormGroup, FormBuilder, Validators, FormControl } from "#angular/forms";
#Component({
selector: 'app-member-form',
templateUrl: './member-form.component.html',
styleUrls: ['./member-form.component.css']
})
export class MemberFormComponent implements OnInit {
registerForm: FormGroup
//submitted = false;
constructor(
private route: ActivatedRoute,
private router: Router,
private memberService: MemberService,
private formBuilder: FormBuilder) {
let formControls = {
surname: new FormControl('', [
Validators.required,
Validators.pattern("[A-Za-z .'-]+"),
]),
name: new FormControl('', [
Validators.required,
Validators.pattern("[A-Za-z .'-]+"),
]),
email: new FormControl('', [
Validators.required,
Validators.email
]),
password: new FormControl('', [
Validators.required
]),
password2: new FormControl('', [
Validators.required,
]),
phone: new FormControl('', [
Validators.required,
Validators.minLength(10),
Validators.maxLength(10),
Validators.pattern("[0-9]+")
]),
}
this.registerForm = this.formBuilder.group(formControls)
}
ngOnInit(): void {}
get name() { return this.registerForm.get('name') }
get surname() { return this.registerForm.get('surname') }
get phone() { return this.registerForm.get('phone') }
get email() { return this.registerForm.get('email') }
get password() { return this.registerForm.get('password') }
get password2() { return this.registerForm.get('password2') }
public onSubmit(): void {
this.memberService.registerMember(this.registerForm.value).subscribe(result => this.gotoMemberList());
}
public gotoMemberList() {
this.router.navigate(['/members']);
}
}
and the html file is:
<link rel="stylesheet" href="member-form.component.css">
<div class="card my-5">
<div class="card-body">
<form [formGroup]="registerForm"(ngSubmit)="onSubmit()"style="border: 2px solid #ccc">
<h1>Sign Up</h1>
<p>Please fill in this form to register</p>
<hr>
<div class="form-group">
<label for="surname"><b>Surname</b></label>
<input formControlName="surname"
id="surname"
type="text"
class="form-control"
placeholder="Enter your surname">
<div *ngIf="surname.touched && surname.invalid">
<small *ngIf="surname.errors.required" class="text-danger">Surname is required</small><br>
<small *ngIf="surname.errors.pattern" class="text-danger">Invalid Surname</small><br>
</div>
</div>
<div class="form-group">
<label for="name"><b>Name</b></label>
<input formControlName="name"
id="name"
type="text"
class="form-control"
placeholder="Enter your name">
<div *ngIf="name.touched && name.invalid">
<small *ngIf="name.errors.required" class="text-danger">Name is required</small><br>
<small *ngIf="name.errors.pattern" class="text-danger">Invalid Name</small><br>
</div>
</div>
<div class="form-group">
<label for="email"><b>Email</b></label>
<input formControlName="email"
id="email"
type="email"
class="form-control"
placeholder="Enter your email address">
<div *ngIf="email.touched && email.invalid">
<small *ngIf="email.errors.required" class="text-danger">Email is required</small><br>
<small *ngIf="email.errors.pattern" class="text-danger">Invalid Email</small><br>
</div>
</div>
<div class="form-group">
<label for="password" class="control-label"><b>Password</b></label>
<input formControlName="password"
id="password"
type="password"
class="form-control"
placeholder="Enter your password">
<div *ngIf="password.touched && password.invalid">
<small *ngIf="password.errors.required" class="text-danger">Password is required</small><br>
</div>
</div>
<div class="form-group">
<label for="password2"><b>Confirm password</b></label>
<input formControlName="password2"
id="password2"
type="password"
class="form-control"
placeholder="Enter your password again">
<div *ngIf="password2.touched && password2.invalid">
<small *ngIf="password2.errors.required" class="text-danger">Password is required</small><br>
</div>
<div *ngIf="password2.valid && password2.value != password.value" class="text-danger">
The passwords entered do not match
</div>
</div>
<div class="form-group">
<label for="phone"><b>Phone Number</b></label>
<input formControlName="phone"
id="phone"
type="tel"
class="form-control"
placeholder="Enter your phone number">
<div *ngIf="phone.touched && phone.invalid">
<small *ngIf="phone.errors.required" class="text-danger">Phone is required<br></small>
<small *ngIf="phone.errors.pattern" class="text-danger">Invalid Phone<br></small>
<small *ngIf="phone.errors.minlength" class="text-danger">Phone must be 10 characters </small>
<!-- <small *ngIf="phone.errors.maxlength" class="text-danger">Phone must contain a maximum of 13 characters</small>-->
</div>
</div>
<br>
<div class="form-group">
<button type="submit" class="btn btn-primary" [disabled]="registerForm.invalid || password.value != password2.value">Sign Up</button>
</div>
</form>
</div>
</div>
Basically, I'm getting an error saying "Object is possibly 'null' on every .errors, .pattern, .required, .invalid, .touched in the *ngIf fields of my html file.
Anyone knows what could be going wrong here?
The reason is a strictNullChecks which is turned on by default.
You can turn it off in tsconfig.json but that is not advised
"angularCompilerOptions": {
"strictNullChecks": false,
...
}
as #CherryDT commented you can add ?. to each reference
or add as first check the object itself in this case surname
<div *ngIf="surname && surname.touched && surname.invalid">
More info: https://blog.angular.io/angular-cli-strict-mode-c94ba5965f63
?. is called "optional chaining" and you can read more about it here
And as i know you can not use it like this "name.touched && name.invalid",
You need to call method of the your form.
check it out
demo angular reactive forms

Angular renders child component in parent view

I have an application in which the user can register an account. After registration he needs to confirm it by entering a code he received in the email.
Follwowing route setup:
const routes: Routes = [
{
path: 'register', component: RegisterComponent, children: [
{path: 'confirm', component: ConfirmRegisterComponent, pathMatch: 'full'}
]
},
];
RegisterComponent.ts:
export class RegisterComponent implements OnInit {
registerForm: FormGroup = new FormGroup({
username: new FormControl('', Validators.required),
email: new FormControl('', Validators.required),
password: new FormControl('', Validators.required)
});
constructor(private authService: AuthService, private router: Router, private route: ActivatedRoute) {
}
ngOnInit(): void {
}
performRegister() {
console.log(this.registerForm.value);
this.authService.register(this.username, this.email, this.password).subscribe(
(response: AbstractResponse) => this.handleResponse(response)
);
}
handleResponse(response: AbstractResponse) {
if (response.status === 200) {
this.router.navigate(['confirm'], {relativeTo: this.route, queryParams: {id: response.payload}})
}
}
get username() {
return this.registerForm.get('password')?.value;
}
get email() {
return this.registerForm.get('email')?.value;
}
get password() {
return this.registerForm.get('password')?.value;
}
}
RegisterComponent.html with router-outlet:
<router-outlet></router-outlet>
<h1>Register</h1>
<form (ngSubmit)="performRegister()" [formGroup]="registerForm">
<div class="form-group">
<label for="username">Username</label><br/>
<input class="form-control" formControlName="username" id="username" name="username" ngModel
placeholder="Username" type="text">
<div *ngIf="username?.invalid && (username?.dirty || username?.touched)"
class="alert alert-danger">
<div *ngIf="username?.errors?.required">
Username is required.
</div>
</div>
<br/>
</div>
<div class="form-group">
<label for="email">Email:</label><br/>
<input class="form-control" formControlName="email" id="email" name="email" ngModel placeholder="Email address"
type="email">
<div *ngIf="email?.invalid && (email?.dirty || email?.touched)"
class="alert alert-danger">
<div *ngIf="email?.errors?.required">
Username is required.
</div>
</div>
<br/>
</div>
<div class="form-group">
<label for="password">Your password:</label> <br/>
<input class="form-control" formControlName="password" id="password" name="password" ngModel
placeholder="Password" type="password">
<div *ngIf="password?.invalid && (password?.dirty || password?.touched)"
class="alert alert-danger">
<div *ngIf="password?.errors?.required">
Username is required.
</div>
</div>
<br/>
</div>
<div class="form-check">
<input class="form-check-input" id="exampleCheck1" type="checkbox">
<label class="form-check-label" for="exampleCheck1">Check me out</label>
</div>
<button [disabled]="!registerForm.valid" class="btn btn-secondary" type="submit">Register</button>
<br/>
<a routerLink="/login">Login</a>
</form>
RegisterConfirmation.ts:
#Component({
selector: 'app-confirm-register',
templateUrl: './confirm-register.component.html',
styleUrls: ['./confirm-register.component.css']
})
export class ConfirmRegisterComponent implements OnInit {
private id!: string;
public confirmationCodeForm: FormGroup = new FormGroup({
code: new FormControl('', Validators.required),
});
constructor(private authService: AuthService, private router: Router, private activatedRoute: ActivatedRoute) {
}
ngOnInit(): void {
this.activatedRoute.queryParams.subscribe(params => {
this.id = params['id'];
})
}
get code() {
return this.confirmationCodeForm.get('code')?.value;
}
performConfirmRegistration() {
this.authService.confirmRegistration(this.id, this.code).subscribe(
(response: AbstractResponse) => this.handleResponse(response)
);
}
handleResponse(response: AbstractResponse) {
if (response.status === 200) {
this.router.navigate(['login'])
}
}
}
and the html:
<h1>Confirm Registration</h1>
<form (ngSubmit)="performConfirmRegistration()" [formGroup]="confirmationCodeForm">
<div class="form-group">
<label for="code">Confirmation Code</label><br/>
<input class="form-control" formControlName="code" id="code" name="code" ngModel
placeholder="XXX-XXX-XXX" type="text">
<div *ngIf="code?.invalid && (code?.dirty || code?.touched)"
class="alert alert-danger">
<div *ngIf="code?.errors?.required">
Confirmation code is required.
</div>
</div>
<br/>
</div>
<button [disabled]="!confirmationCodeForm.valid" class="btn btn-secondary" type="submit">Confirm</button>
<br/>
</form>
But it seems to render both components simultanously which i dont want :/
Can somebody help me on this? I know it works without specifing the confirm as a child of register, but i think it being the child is better.
you can has a router like
const routes: Routes = [
{path: 'register', component: RegisterComponent}
{path: 'register/confirm', component: ConfirmRegisterComponent}
]
and remove the <router-outlet> of the RegisterComponent

Angular form error-TypeError: Class constructor Validators cannot be invoked without 'new'

I'm getting the following angular form error -
ERROR TypeError: Class constructor Validators cannot be invoked without 'new'
at forms.js:1480
at Array.map (<anonymous>)
at _executeValidators (forms.js:1476)
at FormControl.validator (forms.js:1418)
at FormControl._runValidator (forms.js:4089)
at FormControl.updateValueAndValidity (forms.js:4050)
at new FormControl (forms.js:4656)
at FormBuilder.control (forms.js:8951)
at FormBuilder._createControl (forms.js:9011)
at forms.js:8990
Can someone please tell me what I am missing?
My HTML:
<form class="formLogin" [formGroup]="personalForm" (ngSubmit)="onSubmit()">
<div class="form-group rtl">
<label class="col-sm-3 control-label pull-right" for="mail"> your email</label>
<div class="col-sm-9">
<input type="text" formControlName="mail" [value]="person.Email" placeholder="myAddress#gmail.com" class="form-control ltr textBox" email [ngClass]="{ 'is-invalid': submitted && f.mail.errors }" />
<div *ngIf="submitted && f.mail.errors" class="invalid-feedback">
<div *ngIf="f.mail.errors.required">requird</div>
<div *ngIf="f.mail.errors.email">invalid address!</div>
</div></div>
</div>
<br><br>
<div class="form-group rtl">
<label class="col-sm-3 control-label pull-right" for="phone">your phone</label>
<div class="col-sm-9">
<input type="text" formControlName="phone" [value]="person.Phone" class="form-control ltr textBox" placeholder="000-0000000" [ngClass]="{ 'is-invalid': submitted && f.phone.errors }" />
<div *ngIf="submitted && f.phone.errors" class="invalid-feedback">
<div *ngIf="f.phone.errors.required">requird!</div>
<div *ngIf="f.phone.errors.pattern">digits only!</div>
</div></div>
</div>
<br><br>
<div class="form-group rtl">
<label class="col-sm-3 control-label pull-right" for="username">your username</label>
<div class="col-sm-9">
<input type="text" (focus)="incorrectData=false" [value]="person.UserName" formControlName="username" class="form-control textBox " [ngClass]="{ 'is-invalid': submitted && f.username.errors }" />
<div *ngIf="submitted && f.username.errors" class="invalid-feedback">
<div *ngIf="f.username.errors.required">required!</div>
</div></div>
</div>
<br><br>
<div class="form-group rtl">
<label class="col-sm-3 control-label pull-right" for="password">your password</label>
<div class="col-sm-9">
<input type="password" (focus)="incorrectData=false" [value]="person.Password" minlength="6" formControlName="password" class="form-control textBox" [ngClass]="{ 'is-invalid': submitted && f.password.errors }" />
<div *ngIf="submitted && f.password.errors" class="invalid-feedback">
<div *ngIf="f.password.errors.required">requird!</div>
<div *ngIf="f.password.errors.minlength">password length minimum 6 letters!</div>
</div></div>
</div>
<br>
</form>
My ts:
import { Component, OnInit } from '#angular/core';
import { UserService } from '../../../services/user.service';
import { User,UserEnum } from 'src/app/classes/User';
import { FormBuilder, FormGroup,Validators} from '#angular/forms';
#Component({
selector: 'app-personal-details',
templateUrl: './personal-details.component.html',
styleUrls: ['./personal-details.component.css']
})
export class PersonalDetailsComponent implements OnInit {
person:User;
personalForm:FormGroup;
submitted :boolean;
constructor(private userSer:UserService,
private formBuilder: FormBuilder){ }
ngOnInit() {
this.person=this.userSer.userDetailes;
this.personalForm = this.formBuilder.group({
email:['',[Validators.required,Validators.email]],
password: ['', [Validators.required,Validators.minLength(6),Validators]],
username: ['', Validators.required],
phone:['',[Validators.required,Validators.maxLength(10),Validators.minLength(9),Validators.pattern('[0-9]*')]]});}
get f()
{ return this.personalForm.controls; }
saveUser() {}
onSubmit()
{
this.submitted = true;
// stop here if form is invalid
if (this.personalForm.invalid)
{return;}
this.saveUser();}
}
userService:
#Injectable({
providedIn: 'root'
})
export class UserService {
userDetailes:User=null;
}
I have good form imports for my app.module and other forms in my project work well. I think the problem is in this component.
instead of:
password: ['',
[Validators.required,Validators.minLength(6),Validators]],
i had to write:
password: ['',
[Validators.required,Validators.minLength(6),Validators.maxLength(10)]],
just as written above, your problem is because you are referencing the validators in a wrong manner. You need to include the method you are trying to call or invoke. In this case, your line
password: ['', [Validators.required,Validators.minLength(6),Validators]],
Should be
password: ['', [Validators.required,Validators.minLength(6),Validators.maxLength(20)]],// or any other measure you wish to put in place. Validators is the problem here