input values does not fill correctly in FormArray - html

I have trouble with filling the right values into input fields of a FormArray. Here is my html:
<div formArrayName="roles" *ngFor="let role of roles.controls; let i=index">
<div [formGroupName]="i">
<div class="form-group row">
<label class="col-md-2 col-form-label" attr.for="{{'roleNameId' + i}}">Role Name {{i+1}}</label>
<div class="col-md-6">
<input class="form-control"
attr.id="{{'roleNameId' + i}}"
type="text"
formControlName="roleName">
</div>
<label class="col-md-2 col-form-label" attr.for="{{'identifierId' + i}}">
<input
type="checkbox"
attr.id="{{'identifierId' + i}}"
formControlName="identifier"> identifier
</label>
<div class="col-md-2">
<button type="button" (click)="removeRole(i)" class="btn btn-danger oi oi-trash"></button>
</div>
</div>
</div>
</div>
So this html is being rendered x times depending on the number of roles i have. This works just fine and no errors are shown.
But here is the Problem: When i remove one Role which is not the last of the Array, the input fields filled with the right roles change.
Here are the roles:
When i remove role 2 for example, the form looks like this:
role2 was being removed correctly, but role3 disappeared and the last two roles have the name of the last role (role8)
Why this happens? When i look to the formArray where all roles are saved, the array has the correct values, here is the evidence:
why the correct values are not shown in the view? Thank you for your help
EDIT: Here is the relevant typescript code:
this.sourcesForm = this.fb.group({
sourceName: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(255)]],
sourceType: ['QUERY'],
dsl: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(255)]],
list: [''],
roles: this.fb.array([this.buildRole()]),
database: [''],
});
// save roles to temporary variable to map for the roles Formarray
let roles = [];
dslStatement.roles.forEach(role => {
let oneRole = {
roleName: role.name,
identifier: true
}
if (role.role === 'IDENTIFIER')
oneRole.identifier = true;
else
oneRole.identifier = false
roles.push(oneRole);
});
// convert the variable to FormGroups, then the FormGroups to one FormArray
// and at last set the FormArray to the roles of sourcesForm
const rolesFormGroups = roles.map(roles => this.fb.group(roles));
const rolesFormArray = this.fb.array(rolesFormGroups);
this.sourcesForm.setControl('roles', rolesFormArray);
buildRole(): FormGroup {
return this.fb.group({
roleName: '',
identifier: true
});
}
addRole() {
this.roles.push(this.buildRole());
}
removeRole(i: number) {
this.roles.removeAt(i);
console.log(this.roles.value);
console.log(this.roles.controls);
}

UPDATE
I built a stackblitz attempting to demonstrating the issue here: https://stackblitz.com/edit/angular-dk-formarray
It uses Angular 5.0 and does NOT have the problem.
I was able to reproduce this with the app from my course referenced above (Angular 4):
After deleting the "a" row, I get this:
Notice that the "a" is gone, but now I have two "c"s instead of "b" and "c".
Interestingly, if I save and then come back to the page, it displays correctly with "b" and "c".
So it appeared to be a bug that was fixed in Angular 5.
I was able to find a "work around" that worked for me in Angular 4.x:
deleteTag(index: number): void {
this.tags.removeAt(index);
this.productForm.setControl('tags', this.fb.array(this.tags.value || []));
}
You may be able to do something similar to this (but I'm not sure your roles are set up just like my tags?)
But you are probably better off moving to Angular 5.

try this:
addRole() {
this.roles = this.sourcesForm.get('roles') as FormArray;
this.roles.push(this.buildRole());
}
instead of
addRole() {
this.roles.push(this.buildRole());
}

Related

Getting error after upgrading from Angular 8 to 12 - "Property 'controls' does not exist on type 'AbstractControl' "

I had a fully functioning code in Angular 8. I decided to upgrade from 8 to Angular 12.
I have a dynamic reactive form. The form is of question answer format.
Based on who is login in the questions change. The answer is of Yes/No format. Based on who is login in and what answer option is chosen textbox dropdown and checkbox or all the there mentioned appreas.
Here is my code for the form
Component.ts
constructor(
private router: Router,
private datePipe: DatePipe,
private route: ActivatedRoute,
private formBuilder: FormBuilder) {
this.dynamicForm = this.formBuilder.group({
questions: new FormArray([])
});
this.CreateForm();
}
get f() { return this.dynamicForm.controls; }
get t() { return this.f.questions as FormArray; }
CreateForm() {
if (this.formdetail.questionList) {
// CREATE Questions
if (racialQues !== this.formdetail.questionList[i].quetext && this.formdetail.questionList[i].quetext !== auditQues) {
this.t.push(this.formBuilder.group({
quesIndex: [i + 1],
...
controlName: [this.formdetail.questionList[i].selectedAns, [Validators.required]]
}));
} else if (this.formdetail.questionList[i].quetext === auditQues) {
this.t.push(this.formBuilder.group({
quesIndex: [i + 1],
......
selectedValue: [this.formdetail.auditTrail.selectedValue, this.reasonValidator],
}));
} else if (this.formdetail.questionList[i].quetext === racialQues) {
this.t.push(this.formBuilder.group({
quesIndex: [i + 1],
......
selectedAuxAns: [this.formdetail.questionList[i].val, [this.auxAnsValidator]]
}));
}
}
}
Here is the html
<form [formGroup]="dynamicForm">
<!-- Question Start -->
<div *ngFor="let ticket of t.controls; let i = index">
<div [formGroup]="ticket" class="form-row">
<div class="input-group col-md-12" style="padding: .15em .5em">
<div class="input-group-prepend col-md-10" style="padding: 0; margin: 0;">
<label class="input-group-text w-15">{{i + 1}}</label>
<label class="input-group-text w-100" style="text-align: left; white-space: normal;">{{ticket.controls.name.value}}</label>
</div>
<select formControlName="controlName" class="form-control col-md-2" style="height:auto !important;"
[ngClass]="{ 'is-invalid': submitted && ticket.controls.controlName.errors }"
(change)="onChange($event.target.value, i)">
<option [ngValue]="null"> --Select-- </option>
<option *ngFor="let ansItem of formdetail.questionList[i].answerList" [ngValue]="ansItem" >{{ansItem.anstext}}</option>
</select>
<div *ngIf="submitted && ticket.controls.controlName.errors" class="invalid-feedback" style="height:auto !important;"
[ngClass]="{ 'input-group-append': submitted && ticket.controls.controlName.errors,
'col-md-1': submitted && ticket.controls.controlName.errors }">
<div *ngIf="ticket.controls.controlName.errors.required">Required</div>
</div>
.
.
.
.
</div>
/div>
</div>
<!-- Question End -->
</form>
Now I am getting error in "ticket.control"
Property 'controls' does not exist on type 'AbstractControl'.
I am not sure why I am getting this error after upgrade.
I have tried ticket.['control'] or ticket.get('controlName') as suggested by other article of similar error in stackoverflow but nothing works
Here is the snapshot of error
Any help will be appreciated.
Thanks
your t is of type FormArray, FormArray.controls array is of type AbstractControl[], thus, each ticket at
<div *ngFor="let ticket of t.controls; let i = index">
line is of type AbstractControl, which does not have controls property as is seen in TS error in your screenshot. TS does not know that each ticket actually is of type FormGroup (set here this.t.push(this.formBuilder.group({...}) and which has controls property).
So you can try to add another getter tControls:
get f() { return this.dynamicForm.controls; }
get t() { return this.f.questions as FormArray; }
get tControls() { return this.t.controls as FormGroup[]; }
and use it within *ngFor:
<div *ngFor="let ticket of tControls; let i = index">
<div [formGroup]="ticket" class="form-row">
...
Please note, that now [formGroup] will also be properly filled with FormGroup and not AbstarctControl
One of your Angular upgrades probably added
"angularCompilerOptions": {
"fullTemplateTypeCheck": true,
"strictInputTypes": true,
}
to your tsconfig.json file, you can verify it just by setting these values to false and rebuilding your app, but I recommend to leave these strict checks.
This is a generic answer (so generic code) to help fixing such an issue.
Let's suppose you have a loop through a field (call it elements) of type FormArray. This field is part of a form of type FormGroup
In your ts logic code (logic implementation) you should have something like:
form = new FormGroup({
//.. other fields
elements: new FormArray([]),
});
In your template (html file), you need to toop through the elements field:
<li
*ngFor="let element of elements.controls">
{{ element.value }}
</li>
In order to tell angular cli that elements has a property of controls (so of type FormArray), you need to format it in your ts logic code as the following (implement a getter for elements field):
get elements() {
return this.form.get('elements') as FormArray;
}
'controls' isn't a property of an AbstractControl. instead you can use your form group, so 'dynamicForm.controls.controlName'

Reactive form angular using FormArrayName

In my form I need to add phones, I have seen that in the database you are saving a string array with the phone numbers that I added, but the moment the value returned from the database is set to the form, only the first array value is shown .
I would like to display all array values that contain number of phones in string format.
component.html:
<div fxLayout="row" fxLayout.xs="column" fxLayoutAlign="start">
<div formArrayName="phones" fxFlex="30">
<div *ngFor="let phone of phones.controls; index as i">
<mat-form-field>
<input matInput [formControlName]="i" placeholder="Phone Number">
</mat-form-field>
</div>
</div>
<div fxFlex="30">
<button mat-raised-button class="blue" (click)="addPhone()">Add</button>
</div>
</div>
component.ts:
this.myForm = this._formBuilder.group({
phones: new FormArray([new FormControl('')]),
});
this.values$
.pipe(takeUntil(this._unsubscribeAll))
.subscribe((values) => {
// values = {phones: ['999999', '88888', '77777']}
if (values) {
this.myForm.patchValue(values, { emitEvent: false });
}
});
get phones(): FormArray { return this.myForm.get('phones') as FormArray; }
addPhone(): void { this.phones.push(new FormControl('')); }
Even returning more than one value inside the array only displays the first array value on my form, what am I doing wrong?
patchValue won't create any form controls for you, so when you call patchValue it only sets the value for the first form control in your form array, because you only created one.
You have to call addPhone for each phone number or create form inside the describe when you already know how many form controls there should be, but you still need to create as many form controls as number of elements in your array.
this.myForm = this._formBuilder.group({
phones: new FormArray(),
});
this.values$
.pipe(takeUntil(this._unsubscribeAll))
.subscribe((values) => {
if (values && values.phones) {
phones.forEach(phone => this.addPhone(phone));
}
});
get phones(): FormArray { return this.myForm.get('phones') as FormArray; }
addPhone(phone = ''): void { this.phones.push(new FormControl(phone)); }

Working with custom components for input generates "No value accessor for form control with path X->0->Y"

I have a working form taking the following HTML markup. No errors or warnings.
<div class="input-element">
<div class="input-caption">Title</div>
<input type="text"
formControlName="targetField"
class="form-control">
</div>
I transformed it into a custom component, which also works, as shown below.
<app-input-text [info]="'Title'"
formControlName="targetField"
ngDefaultControl></app-input-text>
In my next view, I need to use FormArray as follows - still working code.
<div formArrayName="stuff">
<div *ngFor="let thing of form.controls.stuff.controls; let i = index;"
[formGroupName]=i>
<div class="input-element">
<div class="input-caption">Title</div>
<input type="text"
formControlName="targetField"
class="form-control">
</div>
</div>
</div>
Now, I expected that combining both (i.e. being able to use custom input component and being able to form array for components) would post no problem. However, the sample below doesn't work.
<div formArrayName="stuff">
<div *ngFor="let thing of form.controls.stuff.controls; let i = index;"
[formGroupName]=i>
<app-input-text [info]="'Title'"
formControlName="targetField"
class="col-sm-6"></app-input-text>
</div>
</div>
It generates the following error.
No value accessor for form control with path: 'stuff -> 0 -> targetField'
The custom component is design like this (although given that it works in the explicit markup example, I'm not sure if it's relevant information). The only (wild) guess I have might be that value isn't jacked into the form array field somehow.
export class InputTextComponent implements OnInit {
constructor() { this.value = new EventEmitter<string>(); }
#Input() info: string;
#Output() value: EventEmitter<string>;
onEdit(value: any): void { this.value.emit(value); }
}
The group and array creating in the current view is done like this (not sure if this is of any relevance neither, as it works for the explicit HTML markup case).
this.form = builder.group({
id: "",
stuff: builder.array([
builder.group({ targetField: "aaa" }),
builder.group({ targetField: "bbbb" }),
builder.group({ targetField: "cc" })
])
});
Is there a limitation in Angular in this regard that I'm not aware of? I'm rather sure there's not and that I'm just doing something fairly clever simply missing a tiny detail.
I do understand the error but I can't see how it relates to the code. The form can't find the 0th element in the array or that element has no field of that name. Since I do get to see a few rows, I know there must be a 0th element. Since I specified the name of the field, I know there is indeed such. What else am I missing?

How to use ReactiveFormsModule and validations for dynamically added controls in Angular?

I have a couple of fields connected to the FormBuilder like this.
constructor(private builder: FormBuilder) {
this.form = builder.group({
"firstName": [...],
"lastName": [...]
});
}
In the markup, besides the fix controls, I'll also have an unknown number of input boxes. It's starting with zero and can be increased, as the user clicks on a button, which adds a new input box by each click. There'll be also a removal button for each input box so the number of those is fully dynamic.
<div class="input-caption">FirstName</div>
<input type="text" formControlName="firstName">
<div class="input-caption">LastName</div>
<input type="text" formControlName="lastName">
<div id="options"></div>
<button (click)="addOption()">Add option</button>
As the dynamically added fields need to be validated, I feel that I need to declare them in the group definition. I have no idea how, though.
When I googled, I got a bunch of hits on [(ngModel)] but I also read that it's supposed to be used with the FormsModule and not ReactiveFormsModule as discussed in a blog.
How should I approach it? Is double-bound ngModel the only option?
Edit based on the answer.
HTML
<div *ngFor="let tag of []; let i = index;" [formGroupName]="i">
<div class="input-caption">Tag</div>
<input formControlName="name"> -->
</div>
TS
constructor(private builder: FormBuilder) {
this.form = builder.group({
"firstName": [...],
"lastName": [...],
"tags": this.builder.array([]),
});
}
addTag(): void {
(this.form.controls.tags as FormArray).???;
}
I've also tried to specify a hard-coded array in the markup as follows but didn't get to see any controls being rendered.
<div *ngFor="let tag of [{'name':'uno'},{'name':'duo'}]; let i = index;"
[formGroupName]="i">
<div class="input-caption">Tag</div>
<input formControlName="name"> -->
</div>
Your scenario is the purpose of a FormArray. See the docs here: https://angular.io/guide/reactive-forms#use-formarray-to-present-an-array-of-formgroups
The docs show an array of FormGroups, but you can also use it to create an array of FormControls.
Here is an example from my application:
this.productForm = this.fb.group({
productName: ['', [Validators.required,
Validators.minLength(3),
Validators.maxLength(50)]],
productCode: ['', Validators.required],
starRating: ['', NumberValidators.range(1, 5)],
tags: this.fb.array([]),
description: ''
});
My "tags" look like this:
I set default values into these controls like this:
// Update the data on the form
this.productForm.patchValue({
productName: this.product.productName,
productCode: this.product.productCode,
starRating: this.product.starRating,
description: this.product.description
});
this.productForm.setControl('tags', this.fb.array(this.product.tags || []));
You can find my sample code here: https://github.com/DeborahK/Angular2-ReactiveForms In the "APM" or "APM - Updated" folders.
This is the code from the Pluralsight course: Angular Reactive Forms here: https://app.pluralsight.com/library/courses/angular-2-reactive-forms/table-of-contents
If you just want this code to work, you just need to change it to an array:
<div *ngFor="let tag of ['uno','duo']; let i = index;"
[formGroupName]="i">
<div class="input-caption">{{ tag }}</div>
<input formControlName="name"> -->
</div>
And they don't really need to be form groups. It would probably be simpler if they aren't:
<div *ngFor="let tag of ['uno','duo']">
<div class="input-caption">{{ tag }}</div>
<input [formControlName]="tag"> -->
</div>
And if this is all you need ... then you don't really even need FormArrays.

check if emails match on blur

I'm trying to check if email field and confirm email field match each other. That is, the user types in their email and then they have to confirm it again. I want the match/validation to happen on blur (when the user presses enter or the textfield loses focus).
Here's my ts file:
import {Component, OnInit} from '#angular/core';
import {User} from './user.interface';
import {FormBuilder, FormGroup, ValidatorFn} from '#angular/forms';
#Component({
selector: 'my-email',
templateUrl: '/app/components/profile/email.component.html',
styleUrls:['styles.css'],
})
export class EmailComponent implements OnInit {
public user : User;
Form : FormGroup;
ngOnInit() {
// initialize model here
this.user = {
Email: '',
confirmEmail: ''
}
if(this.Form.valid) {
this.displayErrors = false;
}
}
constructor(fb: FormBuilder, private cookieService: CookieService, private router: Router) {
this.Form = fb.group({
email: [''],
confirmEmail: ['']
},
{
validator: this.matchingEmailsValidator('email', 'confirmEmail')
});
}
save(model: User, isValid: boolean) {
// call API to save customer
//save email
}
matchingEmailsValidator(emailKey: string, confirmEmailKey: string): ValidatorFn {
return (group: FormGroup): {[key: string]: any} => {
let email = group.controls[emailKey];
let confirmEmail = group.controls[confirmEmailKey];
if (email.value !== confirmEmail.value) {
return {
mismatch: true
};
}
};
}
}
Here's my view:
<form [formGroup]="Form" novalidate (ngSubmit)="Form.valid && save(Form.value, Form.valid)">
<div class="container-fluid">
<div id = "container" class="contain" style="text-align: center">
<div>
<fieldset class="form-group">
<label id = "rounded" class="item item-input .col-md-6 .col-md-offset-3">
<input class="email-address-entry form-control" name="email" type="email" placeholder="name#domain.com" formControlName="email" pattern="^(\\w|[0-9.!#$%&’*+/=?^_\`{|}~-])+#(\\w|[0-9-])+(?:‌​[.](\\w|[0-9-])+)*$"/>
</label>
<p class="Reenter-your-email">Reenter your email to confirm</p>
<label id = "rounded" class="item item-input">
<input class="email-address-entry form-control" (blur)="displayErrors=true" name="confirmEmail" type="email" placeholder="name#domain.com" formControlName="confirmEmail" validateEqual="email"/>
</label>
</fieldset>
</div>
<div>
<label class="entry-invalid">
<p *ngIf="displayErrors && !Form.get('email').valid">The email you entered does not match.</p>
</label>
</div>
<div (click)="Form.get('email').length > 0 ? save(Form.value, Form.valid) : NaN" class="{{ Form.get('email').length > 0 ? 'container-fluid anchorBottomHighlight' : 'container-fluid anchorBottom'}}">
<label class="footerLabel">Confirm</label>
</div>
</div>
</div>
</form>
Currently, with the way it's set up, the validation occurs but it does not get cleared when the correct match is input. I'm wondering how I can setup my view correctly? So the validation message is shown/hidden when the correct match is set and not.
Also it seems like Form.get('email').length > 0 is never greater than 0 / never hit, so my label doesn't toggle to be clickable.
I'm using Angular 2 and reactive forms.
It looks that you're mixing the two form syntaxes: template-driven forms and model-driven forms.
Since you're declaring a form model in your class with FormBuilder, I'm assuming you want a model-driven form.
This means your fields don't need attributes like [(ngModel)] or #EmailAddress.
Instead of that:
<input type="email" [(ngModel)]="user.EmailAddress" required #EmailAddress="ngModel">
Write this:
<!-- Now I'm using `formControlName` to bind the field to the model -->
<!-- Its value must match one of the names you used in the FormBuilder -->
<input type="email" formControlName="email">
ALL of your validators must be declared in the FormBuilder. Not just matchingEmailsValidator, but also required:
this.Form = fb.group({
email: ['', Validators.required],
confirmEmail: ['', Validators.required]
},
{
validator: this.matchingEmailsValidator('email', 'confirmEmail')
});
Now you can access a field with the following syntax:
// In the class
this.Form.get('email').value
this.Form.get('email').errors
<!-- In the template -->
{{ Form.get('email').value }}
{{ Form.get('email').errors }}
You can use these syntaxes to display errors. For example:
<input type="email" formControlName="email">
<p *ngIf="Form.get('email').dirty && Form.get('email').errors.required">
This field is required.
</p>
In the example above, I am displaying an error message if the email field has been touched (i.e. the user tried to enter something) AND the required error is present.
You can also verify that your validation rules are enforced by inspecting the form's markup with your browser's dev tools. Angular should have added classes like .ng-invalid or .ng-valid to the <input> tags that have validation rules.
Finally, regarding your question to check email match on blur. You can't postpone Angular's validation, it will happen in real-time (as the user types). But you could wait for the blur event to display errors.
Combining this last advice with my previous example, here's how you could should an error if the email field is empty AND it has lost focus (blur event):
<input type="email" formControlName="email" (blur)="displayErrors=true">
<p *ngIf="displayErrors && Form.get('email').dirty && Form.get('email').errors.required">
This field is required.
</p>
UPDATE(01-FEB-2017) after Euridice posted this Plunkr:
You still have wayyyyy to much validation code in your template. Like I said, ALL VALIDATORS should be declared IN THE FORM MODEL (with the FormBuilder). More specifically:
The pattern="..." attribute in the email field should be replaced with Validators.pattern() in the form model.
What is the validateEqual="email" attribute in the confirmEmail field? You're not using that anywhere.
The main problem is your test to display the error message: *ngIf="displayErrors && !Form.get('email').valid && Form.get('email').error.mismatch".
First of all, the property is errors with an "s", not error.
Also, your custom validator is setting the error on the form itself, NOT on the email field. This means you should retrieve your mismatch custom error from Form.errors.mismatch, NOT Form.get('email').errors.mismatch.
Here's the updated, working Plunkr: https://plnkr.co/edit/dTjcqlm6rZQxA7E0yZLa?p=preview