How to use one component for validation other two components? - javascript

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.

Related

Angular 7 dynamic form validation using reactive forms

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

create dynamic form in angular6

i need to create a dynamic form . when click AddNew it create a new form .
i using this code in ts file :
addinfoForm:FormGroup;
infoNameList:FormArray;
infoModel:Productdetail;
constructor(private fb:FormBuilder,private router:Router,private tokenService:TokenstoreService) { }
ngOnInit() {
this.InfoForm();
}
/**
* AddInfoForm
*/
public InfoForm() {
this.addinfoForm=this.fb.group({
infoName:this.fb.array([this.CreateInfoName()])
})
this.infoNameList=this.addinfoForm.get('infoNames') as FormArray;
}
public CreateInfoName():FormGroup{
return this.fb.group({
infoName:['',Validators.compose([Validators.required])]
});
}
public AddInfoName(){
this.infoNameList.push(this.CreateInfoName());
}
public RemoveInfoName(index:number){
this.infoNameList.removeAt(index);
}
and use this in html :
<div class="panel-content">
<form class="form-line" [formGroup]="addinfoForm" (ngSubmit)="AddRole()">
<div formArrayName="infoNameList">
<div class="description" *ngFor="let name of addinfoForm.controls; let NameIndex=index" [formGroupName]="NameIndex">
<div [formGroupName]="i" class="row">
<label class="form-line"> Name: </label>
<input style="margin-right: 50px;" class="form-line" pInputText id="pFaName" formControlName="Name">
<app-filederrors [form]="addinfoForm"
field="pFaName"
nicename="Name">
</app-filederrors>
</div>
</div>
</div>
</form>
<button (click)="AddInfoName()">Add New </button>
<div class="button">
<button pButton type="button" label="REgister" (click)="AddCat()" [disabled]="!addinfoForm.valid" class="ui-button-rounded"></button>
<button pButton type="button" label="Cencel" class="ui-button-rounded ui-button-danger"></button>
</div>
</div>
but when i click it how me this Error :
AddinfoComponent.html:21 ERROR TypeError: Cannot read property 'push' of null
at AddinfoComponent.push../src/app/admin/admin/dashboard/productinfo/addinfo/addinfo.component.ts.AddinfoComponent.AddInfoName (addinfo.component.ts:41)
How Can i solve this problem ?
Maybe get('infoName') instead of get('infoNames')?
public InfoForm() {
this.addinfoForm=this.fb.group({
infoName:this.fb.array([this.CreateInfoName()])
})
this.infoNameList=this.addinfoForm.get('infoName') as FormArray;
}
The problem is that your infoNameList property has been declared, but not initialised so it's null.
Just do the following:
ngOnInit() {
this.inforNameList = this.fb.array([])
this.InfoForm();
}
wrong name should be infoName
public InfoForm() {
this.addinfoForm=this.fb.group({
infoName:this.fb.array([this.CreateInfoName()])
})
this.infoNameList=this.addinfoForm.get('infoName') as FormArray; // <- previously infoNames
}

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

Angular Forms - What is the correct way to initialize

I have a basic form that I have built with 3 fields. Name, description and id. The data is meant to be populated by a service that calls out to a C# API that returns JSON that is then loaded to the form.
When it opens I get the correct data but I get this error. If I striped out the name input, the errors just move to the description field then the id.
I am still learning Angular, but have read a heap to try and fix this. I think I've got it all right, but I'm guessing it's something to do with initialisation because if I add this code before getting the data from the scenario service, the errors go.
this.scenario = { 'id': 0,
'name': '',
'description': '',
'dateCreated': '',
'createdBy': '',
'dateModified': '',
'modifiedBy': '',
'active': true };
So what is the correct way to code this so my interface is initialised without having to hard code it?
test.component.html
<h1>
Edit Scenario - {{ name.value }}
</h1>
<div class='panel-body'>
<form novalidate
#scenarioForm="ngForm"
(ngSubmit)="saveForm()">
<div class='row'>
<div class='col-md-1'><label for="scenarioName" class="control-label">Name</label></div>
<div class='col-md-6'>
<div class="form-group" [class.has-error]="name.invalid && name.touched">
<input class="form-control"
#name="ngModel"
name="scenarioName"
type="text" maxlength="50" placeholder="Scenario name" required
[(ngModel)]="scenario.name">
</div>
</div>
</div>
<div class='row'>
<div class='col-md-1'><label for="descption">Descption</label></div>
<div class='col-md-6'>
<div class="form-group" [class.has-error]="description.invalid && description.touched">
<textarea #description="ngModel"
ngControl="description"
class="form-control"
rows="4" maxlength="500"
placeholder="What is this scenario for?"
required
name="description"
[(ngModel)]="scenario.description"></textarea>
<div *ngIf="description.invalid && description.dirty" class="alert alert-danger">
Description is required, and must be at least blah blah...
</div>
</div>
</div>
</div>
<div class='panel-footer'>
<button class="btn btn-default" type="submit">Save</button>
</div>
<br><br>
<input #id type="text" name="id" [(ngModel)]="scenario.id" #id="ngModel">
</form>
<div id="debugging">
<br>
Valid? {{scenarioForm.valid}}<br>
Model: {{ scenario | json }} <br>
Model: {{ result | json }}<br>
Form: {{ scenarioForm.value | json }}
<br>
</div>
test.component.ts
import { Component, OnInit, NgModule } from '#angular/core';
import { SharedModule } from './../shared/shared.module';
import { FormsModule, NgForm, FormGroup } from '#angular/forms';
import { CommonModule } from '#angular/common';
import { ScenarioService } from './scenario.service';
import { IScenario } from './scenario';
import { Router, ActivatedRoute } from '#angular/router';
#NgModule({
imports: [
FormsModule
],
exports: [FormsModule]
})
#Component({
selector: 'app-scenario-form',
templateUrl: './test.component.html',
})
export class TestComponent implements OnInit {
// tslint:disable-next-line:no-inferrable-types
private pageTitle: string = 'New Scenario';
scenario: IScenario;
result: IScenario;
constructor(private _scenarioService: ScenarioService,
private _route: ActivatedRoute) {}
ngOnInit() {
const scenarioId = this._route.snapshot.paramMap.get('id');
if (scenarioId) {
this._scenarioService.getScenario(+scenarioId).subscribe(
scenario => this.scenario = scenario);
}
}
}
Since you are getting the response from API asynchronously, you need to handle the null initially, you can do that with safe navigation operator
<input #id type="text" name="id" [(ngModel)]="scenario?.id" #id="ngModel">
same applies for all your fields.
As you mentioned above, other way is to fix via initializing the object Scenario
Since you need to accomplish two way data binding, you need to initialize the object by creating an instance
scenario: IScenarioUpdate = {modifiedBy: ''}

How to show the 'has-error' class on an invalid field in Angular 2

Given:
<div class="form-group" [fieldValidity]="email">
<label for="email" class="sr-only">Email</label>
<input [(ngModel)]="model.email" ngControl="email" required>
</div>
And my custom [fieldValidity] directive:
import { Directive, ElementRef, Input } from 'angular2/core';
import {NgControlName} from 'angular2/common';
#Directive({
selector: '[fieldValidity]'
})
export class FieldValidityDirective {
private el: HTMLElement;
#Input('fieldValidity') field: NgControlName;
constructor(el: ElementRef) {
this.el = el.nativeElement;
}
private _onValidityChange(value: string) {
//TODO test field.valid || field.pristine
if (?) {
this.el.classList.remove('has-error');
} else {
this.el.classList.add('has-error');
}
}
}
How can I get subscribe to the field.valid && field .pristine values to show the error? (I've marked it with 'TODO' below)
An easy way is to use the data-driven approach with the [ngClass] directive as follows
Template:
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<div class="form-group">
<div [ngClass]="{'has-error': form.controls['description'].invalid}">
<input type="text" formControlName="description" class="form-control" required [(ngModel)]="description">
</div>
</div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
Component:
export class FormComponent implements OnInit {
private form: FormGroup;
private description: string;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.form = this.formBuilder.group({
description: new FormControl('')
});
}
}
You could also implement the ngDoCheck method to check the validity:
ngDoCheck(value: string) {
if (field.valid || field.pristine) {
this.el.classList.remove('has-error');
} else {
this.el.classList.add('has-error');
}
}
That said you could implement a wrapping component that leverages ngClass directly on the element. Something like that:
#Component({
selector: 'field',
template: `
<div class="form-group form-group-sm" [ngClass]="{'has-error':state && !state.valid}">
<label for="for" class="col-sm-3 control-label">{{label}}</label>
<div class="col-sm-8">
<!-- Input, textarea or select -->
<ng-content></ng-content>
<span *ngIf="state && !state.valid" class="help-block text-danger">
<span *ngIf="state.errors.required">The field is required</span>
</span>
</div>
</div>
`
})
export class FormFieldComponent {
#Input()
label: string;
#Input()
state: Control;
}
You can even go further by directly referencing the control from the ng-content using the #ContentChild decorator:
#Component({
(...)
})
export class FormFieldComponent {
#Input()
label: string;
#ContentChild(NgFormControl) state;
(...)
}
This way you would be able to define your input this way with ngFormControl (would also work with ngControl):
<form [ngFormModel]="companyForm">
<field label="Name">
<input [ngFormControl]="companyForm.controls.name"
[(ngModel)]="company.name"/>
</field>
</form>
See this article for more details (section "Form component for fields"):
http://restlet.com/blog/2016/02/17/implementing-angular2-forms-beyond-basics-part-2/
Make your validation check a validator like shown in https://angular.io/docs/ts/latest/api/common/FormBuilder-class.html or https://angular.io/docs/ts/latest/cookbook/dynamic-form.html and use a directive like below to set your custom class when Angular sets the ng-invalid class, or just use the ng-invalid class Angular already sets instead of introducing a new one.
#Directive({
selector: 'input'
})
export class AddClass {
#HostBinding('class.has-error')
hasError:boolean = false;
#Input('class') classes;
ngOnChanges() {
this.hasError = classes.split(' ').indexOf('ng-invalid') >= 0);
}
}
You need to add AddClass directive to directives: [AddClass] of the component where you want to use it.

Categories

Resources