Angular 7 dynamic form validation using reactive forms - javascript

I am currently developing a dynamic form builder it has an admin side and a user side, on the admin side you can set the name of the input and type eg: first name and textbox you can add or take away from fields and there are a set amount of types you can choose from, when you are done the admin will then save the form to the Database. On the user frontend the from is pulled from the Database and using patchValue the from is set the problem I am having is with the user's input to the questions on the form. I am trying to figure out how I can first set the type and placeholder of the input that the user uses to answer the questions.
As well as dynamically apply validation rules to each input, so, for instance, a user wants to fill out a form with their first name, last name, age, and CV for the first and last name I want to have required and a regex expression to only allow certain characters, for the age I want to have a min and max number and cv required. and when the user submits the form I only want to send the name and value of an input and not the whole form.
But keep in mind that these forms are completely dynamic so I need to validate the user's input based on the input type that is set
/*Typescript Code*/
import { Component, OnInit } from '#angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '#angular/forms';
import { FormService} from '../form.service';
import { ActivatedRoute } from '#angular/router';
#Component({
selector: 'app-reactive',
templateUrl: './reactive.component.html',
styleUrls: ['./reactive.component.scss']
})
export class ReactiveComponent implements OnInit {
public form: FormGroup;
public fieldList: any;
types: Array<any>;
formData: any;
Param: string;
get contactFormGroup() {
return this.form.get('inputs') as FormArray;
}
constructor(
private route: ActivatedRoute,
private fb: FormBuilder,
private api: FormService) { }
ngOnInit() {
/*First I initlize the form*/
this.form = this.fb.group({
name: [null, Validators.compose([Validators.required])],
organization: [null, Validators.compose([Validators.required])],
inputs: this.fb.array([this.createForm()])
});
this.route.paramMap.subscribe(params => {
this.Param = params.get('id');
this.getForm(this.Param);
});
// set fieldslist to this field
this.fieldList = this.form.get('inputs') as FormArray;
}
// formgroup
/*The I initilize the form array of inputs*/
createForm(): FormGroup {
return this.fb.group({
type: [null, Validators.compose([Validators.required])],/*These come from the DB*/
name: [null, Validators.compose([Validators.required])],/*These come from the DB*/
value: [null, Validators.compose([Validators.required])] /*This gets filled in by the user*/
});
}
/*The I use my API service to call the DB using the form Id*/
getForm(id) {
this.api.getForm(id).subscribe(
(data: any) => this.setForm(data)
);
}
getFieldsFormGroup(index): FormGroup {
const formGroup = this.fieldList.controls[index] as FormGroup;
return formGroup;
}
/*Here I set my form data*/
setForm(data) {
const d = data.results;
this.form.patchValue({
name: [d[0].form_name],
organization: [d[0].org],
});
this.form.setControl('inputs', this.setExistingFields(d[0].fields));
}
/*Here I set my inputs array data*/
setExistingFields(fields: any): FormArray {
const formArray = new FormArray([]);
this.fieldList = formArray;
fields.forEach(f => {
formArray.push(this.fb.group({
name: f.name,
type: f.type,
value: f.value
}));
});
return formArray;
}
submit() {
/* Here when I send my form back to the server I only want to send the inputs name and value nothing else */
console.log(this.form.value.inputs);
}
}
/*HTML CODE*/
<div class="container p-1">
<div class="row">
<div class="col-12">
<form class="md-form" [formGroup]="form" #submittion (submit)="submit()">
<div class="card">
<div class="card-header">Form Name</div>
<div class="card-body">
<div class="row">
<div class="form-group col-6">
<i class="fab fa-wpforms prefix"></i>
<input class="form-control" placeholder="Form Name" formControlName="name" type="text" readonly>
</div>
<div class="form-group col-6">
<i class="far fa-building prefix"></i>
<input class="form-control" placeholder="Organization" formControlName="organization" type="text"
readonly>
</div>
</div>
</div>
<div class="card-header col-12">Please fill in all fields. </div>
<div class="card-body" formArrayName="inputs">
<div class="row">
<div class="col-6" *ngFor="let contact of contactFormGroup.controls; let i = index;">
<div [formGroupName]="i" class="row z-depth-1 m-1 p-1">
<div class="form-group col-6">
<input class="form-control" formControlName="name" type="text" readonly>
</div>
<div class="form-group col-6">
<1-- This is the input that the user will fill in and I am not sure how to dynamically set the type or placeholder this is what I am trying to achieve -->
<input class="form-control" type="" placeholder=""
formControlName="value" />
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="icon-bar round">
<button class="btn btn-success round m-1" type="submit" (click)="submit()"><i class="fas fa-save"> Save Form</i></button>
</div>
Any help is very much appricated on this I have been trying to figure it out for a while now, thank you

Related

How do you add elements and access values dynamically in Angular?

I am working on a small project that allows the user to add dynamic fields. On clicking a button I have been able to create input fields dynamically. I am trying to access the value of each field and push it to the service. On the other hand, another component should make the number of div depending upon the number of input fields created by the user and each div should contain a title depending upon the user input in the input field.
register.component.html
<h2>Demo App</h2>
<form [formGroup]="myForm">
<button (click)="addRooms()">Add Room </button>
<div formArrayName="addRoom">
<div *ngFor="let r of Rooms.controls; let i=index" [formGroupName]="i">
<mat-form-field>
<input matInput placeholder="Enter A Room Name" formControlName="roomName" (keyup)="abc()"/>
</mat-form-field>
<button (click)="deleteRoom(i)">Delete</button>
</div>
</div>
<input type="button" (click)="getRoomValues()" value="Get">
</form>
register.component.ts
import { Component, OnInit} from '#angular/core';
import { RegisterModel } from '../models/register.model';
import {FormGroup, FormBuilder, Validators, FormArray, FormControl } from '#angular/forms';
import { Router } from '#angular/router';
#Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit, AfterViewInit {
myForm: FormGroup;
room: FormGroup;
constructor(private formBuilder:FormBuilder, private r:Router, private _ele:ElementRef, private _render: Renderer) { }
ngOnInit() {
this.myForm = this.formBuilder.group({
addRoom: this.formBuilder.array([]),
tst: new FormControl()
});
}
getVal(){
console.log(this.myForm.value.tst);
}
get Rooms(){
return this.myForm.get('addRoom') as FormArray;
}
addRooms(){
this.room = this.formBuilder.group({
roomName:new FormControl()
})
this.Rooms.push(this.room);
console.log(this.Rooms);
}
abc(){
console.log(this.room.value.roomName);
}
deleteRoom(i){
this.Rooms.removeAt(i);
}
get roomNames(){
return this.myForm.get('roomNames') as FormArray;
}
getRoomValues(){
console.log(this.myForm.value.addRoom)
}
Below is the code sample for couple of fields with dynamic Add & Remove functionality.
<form [formGroup]="linksForm" class="form-horizontal">
<div class="form-group">
<label class="col-md-2 control-label">Links
</label>
<div class="col-md-10">
<div formArrayName="links" *ngFor="let item of linksForm.get('links').controls; let i = index;">
<div [formGroupName]="i">
<div class="col-md-5">
<input class="form-control col-md-5" formControlName="name" placeholder="Name">
</div>
<div class="col-md-5">
<input type="url" pattern="https?://.+" placeholder="http://example.com" class="form-control col-md-5"
formControlName="link">
</div>
<div class="col-md-2">
<button class="btn btn-warning btn-xs m-t-sm" type="button" (click)="removeItem(i)">
<i name="save" class="fa fa-trash"></i>
</button>
<button *ngIf="i == linksForm.get('links').controls.length - 1" class="btn btn-primary btn-xs m-t-sm" type="button" (click)="addItem()">
<i name="save" class="fa fa-plus"></i>
</button>
</div>
</div>
</div>
</div>
</div>
</form>
TS : Declare below variables in class :
linksForm: FormGroup;
links: FormArray;
Inside ngOnInit() initialize form with at least one row :
this.linksForm = new FormGroup({
'links': new FormArray([this.createItem()])
});
Add below functions for Add / Remove :
addItem(): void {
this.links = this.linksForm.get('links') as FormArray;
this.links.push(this.createItem());
}
removeItem(index: any) {
this.links.removeAt(index);
if (this.links.length == 0) {
this.addItem();
}
}
createItem(): FormGroup {
return new FormGroup({
id: new FormControl(),
name: new FormControl(),
link: new FormControl(),
createdAt: new FormControl()
});
}

How to use one component for validation other two components?

I have three components: GalleryAddComponent to add a new element, GalleryItemComponent, to edit an element, FieldsComponent, the form I want to use in the components: GalleryAddComponent and GalleryItemComponent. All components are inside the GalleryComponent. But when I go to the component GalleryAddComponent to add a new element I get the error: ERROR TypeError: Cannot read property 'controls' of undefined. Also in the component: GalleryItemComponent.
Help solve this problem so that the editing and adding logic works correctly.
template of GalleryAddComponent
<div class="card">
<div class="card-body">
<form [formGroup]="angForm" novalidate>
<app-fields [formGroup]="angForm"></app-fields>
<div class="form-group but-group">
<button (click)="addPost(title.value, url.value); angForm.reset(title.value, url.value)"
[disabled]="angForm.pristine || angForm.invalid"
class="btn btn-primary">Add
</button>
<a routerLink="/" class="btn btn-danger">Back</a>
</div>
</form>
</div>
</div>
code of GalleryAddComponent
export class GalleryAddComponent implements OnInit {
angForm: FormGroup;
isAdded: boolean = false;
constructor(private fb: FormBuilder, private galleryService: GalleryService) {}
ngOnInit() {
this.angForm = this.fb.group({
title: ['', Validators.required],
url: ['', Validators.required]
});
}
addPost(title: string, url: string): void {
this.galleryService.add(title, url).subscribe(res => {
this.isAdded = true;
});
}
}
template of GalleryItemComponent
<div class="card" *ngIf="toggleEdit">
<h4>Edit your post</h4>
<div class="card-body">
<form [formGroup]="angForm" novalidate>
<app-fields [formGroup]="angForm"></app-fields>
<div class="form-group but-group">
<input type="button"
(click)="updatePost(title.value, url.value)"
[disabled]=" angForm.invalid"
class="btn btn-primary" value="Update Post">
</div>
</form>
</div>
</div>
code of GalleryItemComponent
export class GalleryItemComponent implements OnInit {
pic: Picture;
angForm: FormGroup;
constructor(private route: ActivatedRoute,
private galleryService: GalleryService, private fb: FormBuilder) {}
ngOnInit() {
this.angForm = this.fb.group({
title: ['', Validators.required],
url: ['', Validators.required]
});
this.showPost();
}
showPost(): void {
this.route.params.subscribe(params => {
this.galleryService.getPicture(params['id']).subscribe(res => {
this.pic = res;
this.angForm.setValue({title: res.title, url: res.url})
})
})
}
updatePost(title: string, url: string): void {
this.route.params.subscribe(params => {
this.galleryService.update(title, url, params['id']).subscribe(res => {
if (res.id === this.pic.id) {
this.pic.title = title;
this.pic.url = url;
}
});
});
}
}
template of FieldsComponent
<div [formGroup]="formGroup">
<div class="form-group">
<label class="col-md-4">Picture Title</label>
<input type="text" class="form-control" formControlName="title" minlength="1" #title/>
</div>
<div *ngIf="angForm.controls['title'].invalid && (angForm.controls['title'].dirty || angForm.controls['title'].touched)"
class="alert alert-danger">
<div *ngIf="angForm.controls['title'].errors.required">
Title is required.
</div>
</div>
<div class="form-group">
<label class="col-md-4">Picture Address (url)</label>
<input type="url" class="form-control" formControlName="url" #url pattern="https?://.+"
title="Include http://"/>
</div>
<div *ngIf="angForm.controls['url'].invalid && (angForm.controls['url'].dirty || angForm.controls['url'].touched)"
class="alert alert-danger">
Address(url) is required.
<div *ngIf="angForm.controls['url'].errors.required ">
</div>
</div>
</div>
code of FieldsComponent
export class FieldsComponent implements OnInit {
#Input() formGroup: FormGroup;
constructor() {}
ngOnInit() {}
}
You are getting this error because you are referencing angForms.controls in your FieldsComponent which only has one variable: formGroup.
Simply replace angForms in the template HTML code with formGroup and the issue should be resolved.
<div [formGroup]="formGroup">
<div class="form-group">
<label class="col-md-4">Picture Title</label>
<input type="text" class="form-control" formControlName="title" minlength="1" #title />
</div>
<div *ngIf="formGroup.controls['title'].invalid && (formGroup.controls['title'].dirty || formGroup.controls['title'].touched)"
class="alert alert-danger">
<div *ngIf="formGroup.controls['title'].errors.required">
Title is required.
</div>
</div>
<div class="form-group">
<label class="col-md-4">Picture Address (url)</label>
<input type="url" class="form-control" formControlName="url" #url pattern="https?://.+" title="Include http://" />
</div>
<div *ngIf="formGroup.controls['url'].invalid && (formGroup.controls['url'].dirty || formGroup.controls['url'].touched)"
class="alert alert-danger">
Address(url) is required.
<div *ngIf="formGroup.controls['url'].errors.required ">
</div>
</div>
</div>
I think the easy solution here, is to set up the formgroup in the parent component, and pass it on to the child components as input, hence it is given to the child component before the child component html is loaded.
The other solution I would recommend is to use the Resolve Technique offered by Angular, this allows you to load all data before a component is loaded with a quite straight-forward setup.
Here are some references:
https://www.techiediaries.com/angular-router-resolve/
https://alligator.io/angular/route-resolvers/
Cannot read property 'controls' of undefined. This error can come only coz instead of formGroup you have used angForm. Try replacing it as shared by #Wrokar. Also what I understand is you want to show consolidated error messages. So instead of doing it in html for each formcontrol, you should do it in component.ts and make it more generic, by subscribing to value change of each control like below, and show the consolidated error message.
for (const field in this.formGroup.controls) { // 'field' is a string
const control = this.form.get(field); // 'control' is a FormControl
control.valueChanges.subscribe(
(res) => {
// check if it is pristine, dirty, invalid, touched, pattern match if
any
// you can access control.errors
// create the consolidated list and append it in the list of error
messages
}
)
}
Its better to make it generic coz, tomorrow your form can have additional fields and then you dont have to change you FieldsComponent.

ERROR Error: Cannot find control with path:

I am leveraging Angular 4's FormBuilder and FormGroup class to create a Form. The form's content is supplied by a GET call with the Questions and Answers structured via JSON format.
Dabbling with my localhost, I see the following error from my web console on page load:
Could anyone with Angular Forms expertise correct this implementation and explain where I went wrong?
Web Console indicates this node from the HTML is causing it:
<fieldset [formGroupName]="i">
For sake of brevity, I'm just providing the bare-bone snippets only down below. Let me know if you need more details.
HTML component:
<form id="form-clinicalscreener" [formGroup]="clinicalForm" (submit)="submitScreenerForm(clinicalForm)" novalidate>
<div formArrayName="Questions">
<div class="section" *ngFor="let tab of clinicalQuestionsResults; let i = index;">
<h2 class="form-title">{{tab.DisplayText}}</h2>
<div>
<div class="form-group" *ngFor="let question of tab.Questions">
<fieldset [formGroupName]="i">
<label>{{question.DisplayText}}</label>
<input type="hidden" formControlName="QuestionId" value="{{question.Id}}" data-value="{{question.Id}}">
<div [ngSwitch]="question.AnswerType">
<div *ngSwitchCase="'Radio'" class="form-group-answers">
<div class="radio" *ngFor="let answer of question.Answers">
<input type="radio"
formControlName="AnswerId"
value="{{answer.Id}}"
data-value="{{answer.Id}}"
class="radio-clinicalscreener">
<label class="label-answer">
<span class="label-answer-text">{{answer.DisplayText}}</span>
</label>
</div>
</div>
<div *ngSwitchCase="'DropDown'" class="form-group-answers">
<select formControlName="AnswerId" class="form-control">
<option value="{{answer.Id}}" data-value="{{answer.Id}}" *ngFor="let answer of question.Answers">{{answer.DisplayText}}</option>
</select>
</div>
</div>
</fieldset>
</div>
</div>
</div>
</div>
<div class="text-center">
<button class="btn btn-screener" type="submit" [disabled]="!clinicalForm.valid">Submit</button>
</div>
TypeScript component:
import { Component, OnInit } from '#angular/core';
import { FormGroup, FormBuilder } from '#angular/forms';
#Component({
selector: '',
templateUrl: '',
styleUrls: ['']
})
export class FormComponent implements OnInit {
// Our model driven form.
clinicalForm: FormGroup;
// Screener Data from API call to be used by view in for loop.
clinicalQuestionsResults: any;
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
// Let's get Clinical Screener metadata.
this.loadClinicalScreener();
// Initialize the form here.
this.clinicalForm = this.formBuilder.group({
Questions: this.formBuilder.array([
this.initQuestions()
])
});
}
private initQuestions() {
// initialize our Questions
return this.formBuilder.group({
QuestionId: [''],
AnswerId: ['']
});
}
private loadClinicalScreener() {
// An AJAX call from a forkJoin() to return the JSON payload, then I assign it to a local object, screenerResponse.
let screenerResponse: any = data[0];
this.clinicalQuestionsResults = screenerResponse.Result.Tabs;
console.log('Here is the metadata for Clinical Screener --->', this.clinicalQuestionsResults);
}
}

When using template driven forms in Angular 2, how to access the form in the component?

I have a simple template driven form like so:
HTML:
<div class="container">
<h1>Hero Form</h1>
<form (ngSubmit)="onSubmit()" #heroForm="ngForm">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" [(ngModel)]="model.name" name="name" #name="ngModel">
</div>
<div class="form-group">
<label for="alterEgo">Alter Ego</label>
<input type="text" class="form-control" id="alterEgo" [(ngModel)]="model.alterEgo" name="alterEgo">
</div>
<div class="form-group">
<label for="power">Hero Power</label>
<select class="form-control" id="power" [(ngModel)]="model.power" name="power">
<option *ngFor="let pow of powers" [value]="pow">{{pow}}</option>
</select>
</div>
<button type="submit" class="btn btn-success" [disabled]="!heroForm.form.valid">Submit</button>
</form>
</div>
Component:
import { Component, OnInit } from '#angular/core';
import { Hero } from './hero';
#Component({
selector: 'at-hero',
templateUrl: './hero.component.html',
styleUrls: ['./hero.component.scss']
})
export class HeroComponent implements OnInit {
constructor() {
//
}
ngOnInit() {
//
}
powers = ['Really Smart', 'Super Flexible', 'Super Hot', 'Weather Changer'];
model = new Hero(18, 'Dr IQ', this.powers[0], 'Chuck Overstreet');
submitted = false;
onSubmit() { this.submitted = true; }
newHero() {
this.model = new Hero(42, '', '');
}
}
How can I:
Reset the whole form from the component (not from the markup)?
Reset a single form field (e.g. the name field) also from the component and not the markup?
You can get the form by using ViewChild
Markup
<form (ngSubmit)="onSubmit()" #heroForm="ngForm">
...
</form>
Component
#ViewChild('heroForm') public heroForm: NgForm;
I suggest you also to look at Reactive Forms too. I think this will be more handy if you want to work with form in the typescript, not in the markup

how to get value from html form and pass is to typescript in angular

Do anyone know how can I get value from HTML forms in typescript?
this is how my html page: login.component.html
<form [formGroup]="loginForm" id="loginForm" (ngSubmit)="authUser()" #userForm="ngForm">
<div class="container">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<p><input type="email" formControlName="email" id="email" placeholder="Your email" [(ngModel)]="user.email" required></p>
</div>
</div>
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<p><input type="password" formControlName="password" id="password" placeholder="Your password" [(ngModel)]="user.password" required></p>
</div>
</div>
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<p><button class="btn btn-primary" type="submit" [disabled]="!bookForm.form.valid">Login</button> </p>
</div>
</div>
</div>
</form>
<div *ngIf="edited" class="alert alert-success box-msg" role="alert">
<strong>Successful Login!</strong>
</div>
and this is my typescript: login.component.ts
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormGroup } from '#angular/forms';
import { Router } from '#angular/router';
import { Http } from '#angular/http';
import { PostsService } from '../posts.service';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
loginForm: FormGroup;
login = false;
users: any;
user = {};
constructor(private fb: FormBuilder, private http: Http, private router: Router, private postsService: PostsService) {
this.postsService.getAllPosts().subscribe(users => {
this.users = users;
});
}
ngOnInit() {
this.loginForm = this.fb.group({
email: 'a#b.com',
password: 'abc123.'
});
}
authUser() {
var i:number;
var email:string = this.loginForm.value.email;
var password:string = this.loginForm.value.password;
var userType:string;
var userEmail:string;
for(i=0;i<this.users.length;i++){
if(this.users[i].email == email && this.users[i].password == password){
this.login = true
userEmail = this.users[i].email;
userType = this.users[i].accountType;
}
}
if(this.login){
console.log("Sucessful");
}
else{
console.log("Unsucessful");
}
}
}
I have tried a lot of methods but none of them seems to work for now my login the way my code words is that once the button is press it will not check whats in the html forms. but it will check againce var email:string = this.loginForm.value.email; and my database for the email and the value thats in var email:string = this.loginForm.value.email; have been hardcoded.
You can try to get value from your ngModel and use .find function to filter your data it's easy and fast to get user details
public userType: string;
public userEmail:string;
public loginUser:any;
authUser() {
this.loginUser = this.users.find(x => x.email == this.user.email && x.password == this.user.password);
if(this.loginUser){
this.login = true
this.userEmail = this.loginUser.email;
this.userType = this.loginUser.accountType;
}
}
You need the prevent default behavior of form. Use following code in your authUser method:
authUser(event) {
event.preventDefault();
//rest of code
}
and update your form tag:
<form [formGroup]="loginForm" id="loginForm" (ngSubmit)="authUser($event)" #userForm="ngForm">
1.- don't mix Reactive form and Template forms.
//with ReactiveForm
<input type="password" formControlName="password" id="password" placeholder="Your password" >
//with template Drive Form
<input type="password" id="password" placeholder="Your password" [(ngModel)]="user.password" required>
2.- with Template driven Form you must have
this.user:any={
email: 'a#b.com',
password: 'abc123.'
}
//And in the submit function you have this.user.email and this.user.password
3.- with Reactive Form
//the validators it's included when create the fbgroup
this.loginForm = this.fb.group({
email: ['a#b.com',Required]
password: ['abc123.',Required]
});
//in the submit pass loginForm as argument
<form [formGroup]="loginForm" id="loginForm" (ngSubmit)="authUser(loginForm)">
//then in your authUser
authUser(form:any){
if (form.valid)
{
console.log(form.value.email,form.value.password)
}
}
4.-You're checking email and password compared with a list of users, but you really have not a list of users. if really post.Service.getAllPost get a list of users the method have a "very bad" name. Ah! put the subscribe in a ngOnInit, not in de constructor
ngOnInit()
{
this.postsService.getAllPosts().subscribe(users => {
this.users = users;
});
....
}

Categories

Resources