How to display error for field that haven't been "touched" on submit - html

I've an angular login, with reactive form:
public form = this.fb.group({
email: ['', [Validators.required, Validators.email]],
name: ['', [Validators.required]],
});
When I click on submit, I do the following:
async createUser() {
if (this.form.valid) {
this.uiService.startBusyIndicator('Adding user...');
try {
await this.userSettingsService.createUser(this.form.get('name')?.value, this.form.get('email')?.value);
this.messageService.add({ severity: 'success', summary: 'User added', detail: 'User added successfully' });
} finally {
this.uiService.stopBusyIndicator();
this.form.reset();
}
} else {
console.log('Marking everything as touched');
this.form.markAllAsTouched();
}
}
Here is my form:
<p-dialog header="Add user" [(visible)]="displayAddForm" [modal]="true">
<form [formGroup]="form" (ngSubmit)="createUser()">
<div class="grid formgrid p-fluid">
<div class="field mb-4 col-12">
<label [for]="name" class="font-medium text-900"> {{ 'account.fields.name' | translate }}</label>
<input required pInputText formControlName="name" #name />
<app-field-errors
[formField]="form.controls['name']"
[fieldName]="'account.fields.name' | translate"></app-field-errors>
</div>
<div class="field mb-4 col-12">
<label [for]="email">{{ 'account.fields.email' | translate }}</label>
<input required pInputText formControlName="email" #email />
<app-field-errors
[formField]="form.controls['email']"
[fieldName]="'account.fields.email' | translate"></app-field-errors>
</div>
</div>
<div class="grid">
<button pButton type="submit" class="col-6 col-offset-6">Add user</button>
</div>
</form>
</p-dialog>
When I click on submit with having nothing as input, nothing changes, my fields still have the ng-pristine and not the ng-dirty classes?
I also tried to call this.form.markAsDirty(); but same result.

While testing I found that if I type some letters and remove them from input fields, they do get highlighted in red, which led to me to the realization that required validator doesn't effect the input fields, if you don't mark them as dirty, when they are in pristine state.
So, if you mark them accordingly, it should work for you, as you can see in this simplified Stacblitz example
component.ts:
form: FormGroup;
displayAddForm = true;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.form = this.fb.group({
email: ['', [Validators.required, Validators.email]],
name: ['', [Validators.required]]
});
}
async createUser() {
if (this.form.valid) {
alert('valid form');
} else {
console.log('Marking everything as touched');
this.form.markAllAsTouched();
for (const key of Object.keys(this.form.controls)) {
if(this.form.controls[key].value.length === 0) {
console.log('blank value');
this.form.controls[key].markAsDirty();
}
}
}
}
component.html:
<p-dialog header="Add User" [(visible)]="displayAddForm" [modal]="true">
<form [formGroup]="form" (ngSubmit)="createUser()">
<div class="grid formgrid p-fluid">
<div class="field mb-4 col-12">
<label [for]="name" class="font-medium text-900"> Name</label>
<input required pInputText formControlName="name" #name />
<div class="error"
*ngIf="form.controls['name'].touched && form.controls['name'].invalid">Name required</div>
</div>
<div class="field mb-4 col-12">
<label [for]="email">Email</label>
<input required pInputText formControlName="email" #email />
<div class="error"
*ngIf="form.controls['email'].touched && form.controls['email'].invalid">Email required</div>
</div>
</div>
<div class="grid">
<button pButton type="submit" class="col-6 col-offset-6">Add user</button>
</div>
</form>
</p-dialog>
Result (after clicking Add User, without touching any of the input fields):

Related

Unable to find the error form is not responding after being rendered

I have created a form Which responded really fin but I don't know what things I have messed in it. it is not responding when I click on submit or reset buttons. I have gone through the code line by line thoroughly but found nothing. I have tried restoring the previous versions but was unable to solve it please help me.
Component.html
<div class="card m-3">
<div class="card-body">
<form [formGroup]="surveyForm" (ngSubmit)="onSubmit()">
<div class="form-group col-5">
<label>UserName:</label>
<input id="name" type="text" formControlName="fName" class="form-control" [ngClass]="{'is-invalid':submitted && f['fName'].errors}"/>
<div *ngIf="submitted && f['fName'].errors" class="invalid-feedback"></div>
<div *ngIf="submitted && surveyForm.controls['fName'].errors" class="form-control">first name is required</div>
</div>
<div class="form-group col-5">
<label>StudentID:</label>
<input placeholder="g01333314" id="StudentId" type="text" formControlName="StudentId" class="form-control" [ngClass]="{'is-invalid':submitted && f['StudentId'].errors}"/>
<div *ngIf="submitted && surveyForm.controls['StudentId'].errors" class="form-control">Enter a valid student id</div>
</div>
<div class="form-group col-5">
<label>Street Address:</label>
<input id="StreetAddress" placeholder="4400 university drive" type="text" formControlName="StreetAddress" class="form-control" [ngClass]="{'is-invalid':submitted && f['StreetAddress'].errors}"/>
<div *ngIf="submitted && surveyForm.controls['StreetAddress'].errors" class="form-control">Enter a valid Address.</div>
</div>
<div class="form-group col-5">
<label>City:</label>
<input id="City" type="text" placeholder="Fairfax" formControlName="City" class="form-control" [ngClass]="{'is-invalid':submitted && f['City'].errors}"/>
<div *ngIf="submitted && surveyForm.controls['City'].errors" class="form-control">Enter a valid city name.</div>
</div>
<div class="form-group col-5">
<label>State:</label>
<input id="State" type="text" placeholder="VA" formControlName="State" class="form-control" [ngClass]="{'is-invalid':submitted && f['State'].errors}"/>
<div *ngIf="submitted && surveyForm.controls['State'].errors" class="form-control">Enter a valid State.</div>
</div>
<div class="form-group col-5">
<label>Zip Code:</label>
<input id="Zip" type="text" placeholder="22030" formControlName="Zip" class="form-control" [ngClass]="{'is-invalid':submitted && f['Zip'].errors}"/>
<div *ngIf="submitted && surveyForm.controls['Zip'].errors" class="form-control">Enter a valid Zip Code.</div>
</div>
<div class="form-group col-5">
<label>Telephone Number:</label>
<input id="Telephone" type="number" placeholder="7039932000" formControlName="Telephone" class="form-control" [ngClass]="{'is-invalid':submitted && f['Telephone'].errors}"/>
<div *ngIf="submitted && surveyForm.controls['Telephone'].errors" class="form-control">Enter a valid Telephone number.</div>
</div>
<div class="form-group col-5">
<label>Email:</label>
<input id="Email" type="email" placeholder="abc#domain.com" formControlName="Email" class="form-control" [ngClass]="{'is-invalid':submitted && f['Email'].errors}"/>
<div *ngIf="submitted && surveyForm.controls['Email'].errors" class="form-control">Enter a valid Email.</div>
</div>
<div class="form-group col-5">
<label>URL:</label>
<input id="Url" type="url" placeholder="https://www.google.com" formControlName="Url" class="form-control" [ngClass]="{'is-invalid':submitted && f['Url'].errors}"/>
<div *ngIf="submitted && surveyForm.controls['Url'].errors" class="form-control">Enter a URL</div>
</div>
<div class="text-center">
<button type="button" class="btn btn-primary mr-1" (click)="onSubmit()">Submit</button>
<button type="button" class="btn btn-secondary" (click)="onReset()">Reset</button>
</div>
</form>
</div></div>
Component.ts
import { Component, OnInit } from '#angular/core';
import { FormControl, FormBuilder, FormGroup, Validators} from '#angular/forms';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
surveyForm!: FormGroup;
submitted= false;
constructor(private formBuilder: FormBuilder){}
ngOnInit(){
const reg = '(https?://)?([\\da-z.-]+)\\(.|:)([a-z.]{2,6})[/\\w .-#$#%&]*/?';
this.surveyForm = this.formBuilder.group({
fName: ['',[Validators.required, Validators.pattern(/^[a-zA-Z ]{2,30}$/)]],
StudentId: ['', [Validators.required, Validators.pattern(/^[A-Za-z]{1,1}\d{8,8}$/)]],
StreetAddress: ['', [Validators.required, Validators.pattern(/^(?:[0-9]+\s[a-zA-Z]|[A-Za-z]+\s[0-9])[a-z0-9\s]*$/)]],
City: ['', [Validators.required, Validators.minLength(3), Validators.pattern(/^[a-zA-Z]*$/)]],
State: ['',[Validators.required, Validators.pattern(/(^[a-zA-Z]{2,2})*$/)]],
Zip: ['',[Validators.required, Validators.minLength(5), Validators.maxLength(5), Validators.pattern(/^[0-9]*$/)]],
Telephone: ['',[Validators.required, Validators.minLength(10), Validators.maxLength(10), Validators.pattern(/^[0-9]*$/)]],
Email: ['', [Validators.required, Validators.pattern(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/)]],
Url: ['',[Validators.required, Validators.pattern(reg)]]
//Date: ['',[Validators.required]]
});
}
//name = new FormControl('');
get f() { return this.surveyForm.controls; }
onSubmit() {
this.submitted = true;
// stop here if form is invalid
if (this.surveyForm.invalid) {
alert('invalid details');
}
else
// display form values on success
alert('SUCCESS!! :-)\n\n' + JSON.stringify(this.surveyForm.value, null, 4));
}
onReset() {
this.submitted = false;
this.surveyForm.reset();
}
}
Something is wrong with your regex that you assign to your reg variable inside your ngOnInit. Your code works if you delete the validator that regex is used in.
ngOnInit(){
const reg = '(https?://)?([\\da-z.-]+)\\(.|:)([a-z.]{2,6})[/\\w .-#$#%&]*/?';
this.surveyForm = this.formBuilder.group({
fName: ['',[Validators.required, Validators.pattern(/^[a-zA-Z ]{2,30}$/)]],
StudentId: ['', [Validators.required, Validators.pattern(/^[A-Za-z]{1,1}\d{8,8}$/)]],
StreetAddress: ['', [Validators.required, Validators.pattern(/^(?:[0-9]+\s[a-zA-Z]|[A-Za-z]+\s[0-9])[a-z0-9\s]*$/)]],
City: ['', [Validators.required, Validators.minLength(3), Validators.pattern(/^[a-zA-Z]*$/)]],
State: ['',[Validators.required, Validators.pattern(/(^[a-zA-Z]{2,2})*$/)]],
Zip: ['',[Validators.required, Validators.minLength(5), Validators.maxLength(5), Validators.pattern(/^[0-9]*$/)]],
Telephone: ['',[Validators.required, Validators.minLength(10), Validators.maxLength(10), Validators.pattern(/^[0-9]*$/)]],
Email: ['', [Validators.required, Validators.pattern(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/)]],
// This enclosed part of the line leads to your problem
// ----------------------------vvvvvvvvvvvvvvvvvvvvvvv---------------------
Url: ['',[Validators.required, Validators.pattern(reg)]]
// ----------------------------^^^^^^^^^^^^^^^^^^^^^^^---------------------
//Date: ['',[Validators.required]]
});
}
I'm not entirely sure on what is wrong with that regex - especially since you provide it as a string, not a regex. Maybe if you provide what that regex should do I can expand on this answer.
See this working StackBlitz, which contains your code with only that single line commented out.

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 validations showing during the page load

We are working on the Angular 4 form and set some validations on the input field but the validation is showing when the page load's but we want the validation when the form is submitted or the field is not valid or filled.
Component.html
<div class="headerbutton-group row">
<i class="fa fa-save header-buttons" tooltip ="Save" tabindex="1" (click)="onSave($event)"></i>
<i class="fa fa-close header-buttons" tooltip ="Close" (click)="onCancel($event)"></i>
</div>
<form [formGroup]="editForm" class="col-md-12 ">
<div class="form-group row">
<div class="col-md-6 padding-Mini">
<label class="col-md-12 col-form-label padding-bottom-Mini" for="txtName">Name</label>
<div class="col-md-12">
<input type="text" id="txtName" name="txtName" class="form-control" placeholder="Name" formControlName="name" [class.is-invalid]="!editForm.controls.name.valid" [class.is-valid]="editForm.controls.name.valid" required>
<div class="invalid-feedback" [style.visibility]=
"editForm.controls.name.valid ? 'hidden':'visible'"> Name is required</div>
</div>
</div>
<div class="col-md-6 padding-Mini">
<label class="col-md-12 col-form-label padding-bottom-Mini" for="txtName">Description</label>
<div class="col-md-12">
<input type="text" id="txtDescription" name="txtDescription" class="form-control"
placeholder="Description" formControlName="description">
</div>
</div>
</div>
</form>
Component.ts
#Component({
selector: 'app-edit-form',
templateUrl: './component.html'
})
export class LoginFormComponent implements OnInit {
constructor(fb:FormBuilder) {
public editForm: FormGroup = new FormGroup({
name : new FormControl('', Validators.required),
description : new FormControl(''),
});
}
public onSave(e): void {
if (this.editForm.valid) {
e.preventDefault();
this.save.emit(this.editForm.value);
} else {
this.validateAllFormFields(this.editForm);
}
}
public onCancel(e): void {
e.preventDefault();
this.closeForm();
}
private validateAllFormFields(formGroup: FormGroup) {
Object.keys(formGroup.controls).forEach(field => {
const control = formGroup.get(field);
if (control instanceof FormControl) {
control.markAsTouched({ onlySelf: true });
} else if (control instanceof FormGroup) {
this.validateAllFormFields(control);
}
});
}
}
// Tried this too editForm.controls.name.pristine
We don't know what we are missing. Kindly help us, with useful documents/ Demo's.
try changing this
<div class="invalid-feedback" [style.visibility]="editForm.controls.name.valid ? 'hidden':'visible'">
Name is required
</div>
to this
<div class="invalid-feedback" *ngIf="!editForm.controls.name.valid && editForm.controls.name.touched">
Name is required
</div>
adding a test on "touched" will fix your problem !

Get a id from the formbuilder to delete a row in Angular 6

I have a HTML page with a few forms to fill in for the user:
<div class="card-body">
<form [formGroup]="FormCar" (ngSubmit)="AddCar(FormCar.value)">
<input type="hidden" formControlName="CarId" id="carId" />
<div class="row">
<div class="form-group col-sm-3">
<label>Brand</label>
<input type="text" class="form-control" formControlName="Brand" id="brand" placeholder="Enter brand">
</div>
</div>
<div class="row">
<div class="form-group col-sm-3">
<label>Model</label>
<input type="text" class="form-control" formControlName="Model" id="model" placeholder="Enter model">
</div>
</div>
<div class="row">
<div class="form-group col-sm-3">
<label>Color</label>
<input type="text" class="form-control" formControlName="Color" id="color" placeholder="Enter color">
</div>
</div>
<div class="row">
<div class="form-group col-sm-3">
<label>Speed</label>
<input type="number" class="form-control" formControlName="TopSpeed" id="topSpeed" placeholder="Enter speed">
</div>
</div>
<div class="btn-group mr-2">
<button type="submit" class="btn btn-danger mr-1">Save changes</button>
<button type="reset" class="btn btn-danger mr-1">New record</button>
<button type="button" class="btn btn-danger mr-1" (click)="DeleteCar(CarId)">Delete</button>
</div>
</form>
</div>
I use a HTML table to display data and when the user clicks on a row it fill with the inputs information. I used this method to fill the fields:
EditCar(carId: number) {
this.carservice.getCarById(carId).subscribe((res: any) => {
this.FormCar.patchValue({
CarId: res.carId,
Brand: res.brand,
Model: res.model,
Color: res.color,
TopSpeed: res.topSpeed
})
});
}
This is working good I have build my form with formbuilder like this:
buildFormCar() {
this.FormCar = this.formBuilder.group({
CarId: ['', Validators.required],
Brand: ['', Validators.required],
Model: ['', Validators.required],
Color: ['', Validators.required],
TopSpeed: ['', Validators.required],
});
}
After the fields are filled I want to delete it by his id and I use this method for it:
DeleteCar(carId: string) {
if (confirm("Weet u zeker?")) {
this.carservice.deleteCar(carId).subscribe(() => {
this.GetCar();
this.GetCarCount();
})
}
}
When I click on the delete button I get a error on the backend (I use .NET core)
This is the error message:
System.InvalidOperationException: 'The property 'CarId' on entity type
'Car' has a temporary value while attempting to change the entity's
state to 'Deleted'. Either set a permanent value explicitly or ensure
that the database is configured to generate values for this property.'
The method that I use in the backend look like this:
[Route("DeleteCar")]
[HttpDelete]
public IActionResult Delete(long id)
{
_context.Cars.Remove(new Car() { CarId = id });
_context.SaveChanges();
return Ok();
}
It seems it cannot find the carId when the delete happens.
Can someone point me in the right direction?
Try FormCar.get("CarId").value like this:
<button type="button" class="btn btn-danger mr-1" (click)="DeleteCar(FormCar.get("CarId").value)">Delete</button>
or Donot pass any parameter in DeleteCar() and do this:
DeleteCar() {
if (confirm("Weet u zeker?")) {
this.carservice.deleteCar(this.FormCar.get("CarId").value).subscribe(() => {
this.GetCar();
this.GetCarCount();
})
}
}

Angular 6 file upload with other form data

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
};
}