Angular reactive form validation with dynamically named controls
In my Angular 7 app using reactive forms I'm creating input
elements based on an *ngFor
loop, so I end up with an input dynamically named:
<nav class="level" *ngFor="let work of workLeft">
<input [formControlName]="work.abbrev">
which of course works fine, but now I'm trying to add the validation error messages to the form, but I'm not sure how to "address" the item. For example, the div would normally look like so:
<div *ngIf="name.errors.required">
but I don't have name
there as it's the dynamic work.abbrev
value. What's the right way to handle this?
You can see my attempt here: https://stackblitz.com/edit/angular-8zevc1
angular angular-reactive-forms angular7 angular2-form-validation
|
show 2 more comments
In my Angular 7 app using reactive forms I'm creating input
elements based on an *ngFor
loop, so I end up with an input dynamically named:
<nav class="level" *ngFor="let work of workLeft">
<input [formControlName]="work.abbrev">
which of course works fine, but now I'm trying to add the validation error messages to the form, but I'm not sure how to "address" the item. For example, the div would normally look like so:
<div *ngIf="name.errors.required">
but I don't have name
there as it's the dynamic work.abbrev
value. What's the right way to handle this?
You can see my attempt here: https://stackblitz.com/edit/angular-8zevc1
angular angular-reactive-forms angular7 angular2-form-validation
IsworkLeft
some sort of aFormArray
? If not, I recommend it to be one. That way you can create aget
ter on your Component Class and use theat
API on aFormArray
to get the relevantFormControl
/FormGroup
– SiddAjmera
Nov 20 '18 at 19:53
No, it's just an array of objects that was returned from an http webservice. But it's not a class variable, it's just created in the call that generates the form data.
– Gargoyle
Nov 20 '18 at 19:54
I'm not sure how your comment helps though as I'm asking about how to deal with it in the HTML itself, and I specifically mentioned not wanting to use a FormArray.
– Gargoyle
Nov 20 '18 at 19:58
1
That's becauseFormArray
is something that is generally used in such scenarios. You want to show validation errors for each item inworkLeft
and it again is a form control. Also, I don't think you will need to keep any mapping to track the index and the form control anywhere. That's not how it works.
– SiddAjmera
Nov 20 '18 at 20:02
OK, if it's the right way so be it. Can you show me what the div's *ngIf should look like please?
– Gargoyle
Nov 20 '18 at 20:03
|
show 2 more comments
In my Angular 7 app using reactive forms I'm creating input
elements based on an *ngFor
loop, so I end up with an input dynamically named:
<nav class="level" *ngFor="let work of workLeft">
<input [formControlName]="work.abbrev">
which of course works fine, but now I'm trying to add the validation error messages to the form, but I'm not sure how to "address" the item. For example, the div would normally look like so:
<div *ngIf="name.errors.required">
but I don't have name
there as it's the dynamic work.abbrev
value. What's the right way to handle this?
You can see my attempt here: https://stackblitz.com/edit/angular-8zevc1
angular angular-reactive-forms angular7 angular2-form-validation
In my Angular 7 app using reactive forms I'm creating input
elements based on an *ngFor
loop, so I end up with an input dynamically named:
<nav class="level" *ngFor="let work of workLeft">
<input [formControlName]="work.abbrev">
which of course works fine, but now I'm trying to add the validation error messages to the form, but I'm not sure how to "address" the item. For example, the div would normally look like so:
<div *ngIf="name.errors.required">
but I don't have name
there as it's the dynamic work.abbrev
value. What's the right way to handle this?
You can see my attempt here: https://stackblitz.com/edit/angular-8zevc1
angular angular-reactive-forms angular7 angular2-form-validation
angular angular-reactive-forms angular7 angular2-form-validation
edited Dec 2 '18 at 10:14
Goncalo Peres
1,3261318
1,3261318
asked Nov 20 '18 at 19:52
Gargoyle
2,71542649
2,71542649
IsworkLeft
some sort of aFormArray
? If not, I recommend it to be one. That way you can create aget
ter on your Component Class and use theat
API on aFormArray
to get the relevantFormControl
/FormGroup
– SiddAjmera
Nov 20 '18 at 19:53
No, it's just an array of objects that was returned from an http webservice. But it's not a class variable, it's just created in the call that generates the form data.
– Gargoyle
Nov 20 '18 at 19:54
I'm not sure how your comment helps though as I'm asking about how to deal with it in the HTML itself, and I specifically mentioned not wanting to use a FormArray.
– Gargoyle
Nov 20 '18 at 19:58
1
That's becauseFormArray
is something that is generally used in such scenarios. You want to show validation errors for each item inworkLeft
and it again is a form control. Also, I don't think you will need to keep any mapping to track the index and the form control anywhere. That's not how it works.
– SiddAjmera
Nov 20 '18 at 20:02
OK, if it's the right way so be it. Can you show me what the div's *ngIf should look like please?
– Gargoyle
Nov 20 '18 at 20:03
|
show 2 more comments
IsworkLeft
some sort of aFormArray
? If not, I recommend it to be one. That way you can create aget
ter on your Component Class and use theat
API on aFormArray
to get the relevantFormControl
/FormGroup
– SiddAjmera
Nov 20 '18 at 19:53
No, it's just an array of objects that was returned from an http webservice. But it's not a class variable, it's just created in the call that generates the form data.
– Gargoyle
Nov 20 '18 at 19:54
I'm not sure how your comment helps though as I'm asking about how to deal with it in the HTML itself, and I specifically mentioned not wanting to use a FormArray.
– Gargoyle
Nov 20 '18 at 19:58
1
That's becauseFormArray
is something that is generally used in such scenarios. You want to show validation errors for each item inworkLeft
and it again is a form control. Also, I don't think you will need to keep any mapping to track the index and the form control anywhere. That's not how it works.
– SiddAjmera
Nov 20 '18 at 20:02
OK, if it's the right way so be it. Can you show me what the div's *ngIf should look like please?
– Gargoyle
Nov 20 '18 at 20:03
Is
workLeft
some sort of a FormArray
? If not, I recommend it to be one. That way you can create a get
ter on your Component Class and use the at
API on a FormArray
to get the relevant FormControl
/FormGroup
– SiddAjmera
Nov 20 '18 at 19:53
Is
workLeft
some sort of a FormArray
? If not, I recommend it to be one. That way you can create a get
ter on your Component Class and use the at
API on a FormArray
to get the relevant FormControl
/FormGroup
– SiddAjmera
Nov 20 '18 at 19:53
No, it's just an array of objects that was returned from an http webservice. But it's not a class variable, it's just created in the call that generates the form data.
– Gargoyle
Nov 20 '18 at 19:54
No, it's just an array of objects that was returned from an http webservice. But it's not a class variable, it's just created in the call that generates the form data.
– Gargoyle
Nov 20 '18 at 19:54
I'm not sure how your comment helps though as I'm asking about how to deal with it in the HTML itself, and I specifically mentioned not wanting to use a FormArray.
– Gargoyle
Nov 20 '18 at 19:58
I'm not sure how your comment helps though as I'm asking about how to deal with it in the HTML itself, and I specifically mentioned not wanting to use a FormArray.
– Gargoyle
Nov 20 '18 at 19:58
1
1
That's because
FormArray
is something that is generally used in such scenarios. You want to show validation errors for each item in workLeft
and it again is a form control. Also, I don't think you will need to keep any mapping to track the index and the form control anywhere. That's not how it works.– SiddAjmera
Nov 20 '18 at 20:02
That's because
FormArray
is something that is generally used in such scenarios. You want to show validation errors for each item in workLeft
and it again is a form control. Also, I don't think you will need to keep any mapping to track the index and the form control anywhere. That's not how it works.– SiddAjmera
Nov 20 '18 at 20:02
OK, if it's the right way so be it. Can you show me what the div's *ngIf should look like please?
– Gargoyle
Nov 20 '18 at 20:03
OK, if it's the right way so be it. Can you show me what the div's *ngIf should look like please?
– Gargoyle
Nov 20 '18 at 20:03
|
show 2 more comments
1 Answer
1
active
oldest
votes
I suggest using FormArray
for this. With FormArray
, here's how your implementation is going to look like:
For the Component Class:
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormArray } from '@angular/forms';
export interface Data {
abbrev: string;
max: number;
}
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
workForm: FormGroup;
workLeft: any;
constructor(private fb: FormBuilder) {}
ngOnInit () {
this.workForm = this.fb.group({
points: this.fb.array()
});
this.fillFormArray();
}
private fakeWebserviceCall(): Data {
return [
{ abbrev: 'foo', max: 12 },
{ abbrev: 'bar', max: 10 }
];
}
private fillFormArray() {
this.workLeft = this.fakeWebserviceCall();
const formControlsArray = this.workLeft.map(work => this.fb.control(work.abbrev, [Validators.min(0), Validators.max(work.max)]));
formControlsArray.forEach(control => this.points.push(control));
console.log(this.workForm.value);
}
get points(): FormArray {
return <FormArray>this.workForm.get('points');
}
pointAt(index) {
return (<FormArray>this.workForm.get('points')).at(index);
}
}
And in the template:
<form [formGroup]="workForm">
<div formArrayName="points">
<div *ngFor="let point of points.controls; let i = index">
{{ workLeft[i].abbrev }}: <input type="number" [formControlName]="i">
<div *ngIf="pointAt(i).invalid && (pointAt(i).dirty || pointAt(i).touched)">
The field is invalid
</div>
</div>
</div>
</form>
Here's a Sample StackBlitz for your ref.
PS: I've made a few updates to the StackBlitz that you've shared including things that Angular Style Guide recommends along with the actual solution. Hope that helps.
Thanks, appreciate the help!
– Gargoyle
Nov 20 '18 at 21:40
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53400565%2fangular-reactive-form-validation-with-dynamically-named-controls%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
I suggest using FormArray
for this. With FormArray
, here's how your implementation is going to look like:
For the Component Class:
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormArray } from '@angular/forms';
export interface Data {
abbrev: string;
max: number;
}
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
workForm: FormGroup;
workLeft: any;
constructor(private fb: FormBuilder) {}
ngOnInit () {
this.workForm = this.fb.group({
points: this.fb.array()
});
this.fillFormArray();
}
private fakeWebserviceCall(): Data {
return [
{ abbrev: 'foo', max: 12 },
{ abbrev: 'bar', max: 10 }
];
}
private fillFormArray() {
this.workLeft = this.fakeWebserviceCall();
const formControlsArray = this.workLeft.map(work => this.fb.control(work.abbrev, [Validators.min(0), Validators.max(work.max)]));
formControlsArray.forEach(control => this.points.push(control));
console.log(this.workForm.value);
}
get points(): FormArray {
return <FormArray>this.workForm.get('points');
}
pointAt(index) {
return (<FormArray>this.workForm.get('points')).at(index);
}
}
And in the template:
<form [formGroup]="workForm">
<div formArrayName="points">
<div *ngFor="let point of points.controls; let i = index">
{{ workLeft[i].abbrev }}: <input type="number" [formControlName]="i">
<div *ngIf="pointAt(i).invalid && (pointAt(i).dirty || pointAt(i).touched)">
The field is invalid
</div>
</div>
</div>
</form>
Here's a Sample StackBlitz for your ref.
PS: I've made a few updates to the StackBlitz that you've shared including things that Angular Style Guide recommends along with the actual solution. Hope that helps.
Thanks, appreciate the help!
– Gargoyle
Nov 20 '18 at 21:40
add a comment |
I suggest using FormArray
for this. With FormArray
, here's how your implementation is going to look like:
For the Component Class:
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormArray } from '@angular/forms';
export interface Data {
abbrev: string;
max: number;
}
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
workForm: FormGroup;
workLeft: any;
constructor(private fb: FormBuilder) {}
ngOnInit () {
this.workForm = this.fb.group({
points: this.fb.array()
});
this.fillFormArray();
}
private fakeWebserviceCall(): Data {
return [
{ abbrev: 'foo', max: 12 },
{ abbrev: 'bar', max: 10 }
];
}
private fillFormArray() {
this.workLeft = this.fakeWebserviceCall();
const formControlsArray = this.workLeft.map(work => this.fb.control(work.abbrev, [Validators.min(0), Validators.max(work.max)]));
formControlsArray.forEach(control => this.points.push(control));
console.log(this.workForm.value);
}
get points(): FormArray {
return <FormArray>this.workForm.get('points');
}
pointAt(index) {
return (<FormArray>this.workForm.get('points')).at(index);
}
}
And in the template:
<form [formGroup]="workForm">
<div formArrayName="points">
<div *ngFor="let point of points.controls; let i = index">
{{ workLeft[i].abbrev }}: <input type="number" [formControlName]="i">
<div *ngIf="pointAt(i).invalid && (pointAt(i).dirty || pointAt(i).touched)">
The field is invalid
</div>
</div>
</div>
</form>
Here's a Sample StackBlitz for your ref.
PS: I've made a few updates to the StackBlitz that you've shared including things that Angular Style Guide recommends along with the actual solution. Hope that helps.
Thanks, appreciate the help!
– Gargoyle
Nov 20 '18 at 21:40
add a comment |
I suggest using FormArray
for this. With FormArray
, here's how your implementation is going to look like:
For the Component Class:
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormArray } from '@angular/forms';
export interface Data {
abbrev: string;
max: number;
}
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
workForm: FormGroup;
workLeft: any;
constructor(private fb: FormBuilder) {}
ngOnInit () {
this.workForm = this.fb.group({
points: this.fb.array()
});
this.fillFormArray();
}
private fakeWebserviceCall(): Data {
return [
{ abbrev: 'foo', max: 12 },
{ abbrev: 'bar', max: 10 }
];
}
private fillFormArray() {
this.workLeft = this.fakeWebserviceCall();
const formControlsArray = this.workLeft.map(work => this.fb.control(work.abbrev, [Validators.min(0), Validators.max(work.max)]));
formControlsArray.forEach(control => this.points.push(control));
console.log(this.workForm.value);
}
get points(): FormArray {
return <FormArray>this.workForm.get('points');
}
pointAt(index) {
return (<FormArray>this.workForm.get('points')).at(index);
}
}
And in the template:
<form [formGroup]="workForm">
<div formArrayName="points">
<div *ngFor="let point of points.controls; let i = index">
{{ workLeft[i].abbrev }}: <input type="number" [formControlName]="i">
<div *ngIf="pointAt(i).invalid && (pointAt(i).dirty || pointAt(i).touched)">
The field is invalid
</div>
</div>
</div>
</form>
Here's a Sample StackBlitz for your ref.
PS: I've made a few updates to the StackBlitz that you've shared including things that Angular Style Guide recommends along with the actual solution. Hope that helps.
I suggest using FormArray
for this. With FormArray
, here's how your implementation is going to look like:
For the Component Class:
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormArray } from '@angular/forms';
export interface Data {
abbrev: string;
max: number;
}
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
workForm: FormGroup;
workLeft: any;
constructor(private fb: FormBuilder) {}
ngOnInit () {
this.workForm = this.fb.group({
points: this.fb.array()
});
this.fillFormArray();
}
private fakeWebserviceCall(): Data {
return [
{ abbrev: 'foo', max: 12 },
{ abbrev: 'bar', max: 10 }
];
}
private fillFormArray() {
this.workLeft = this.fakeWebserviceCall();
const formControlsArray = this.workLeft.map(work => this.fb.control(work.abbrev, [Validators.min(0), Validators.max(work.max)]));
formControlsArray.forEach(control => this.points.push(control));
console.log(this.workForm.value);
}
get points(): FormArray {
return <FormArray>this.workForm.get('points');
}
pointAt(index) {
return (<FormArray>this.workForm.get('points')).at(index);
}
}
And in the template:
<form [formGroup]="workForm">
<div formArrayName="points">
<div *ngFor="let point of points.controls; let i = index">
{{ workLeft[i].abbrev }}: <input type="number" [formControlName]="i">
<div *ngIf="pointAt(i).invalid && (pointAt(i).dirty || pointAt(i).touched)">
The field is invalid
</div>
</div>
</div>
</form>
Here's a Sample StackBlitz for your ref.
PS: I've made a few updates to the StackBlitz that you've shared including things that Angular Style Guide recommends along with the actual solution. Hope that helps.
answered Nov 20 '18 at 21:10
SiddAjmera
13k31137
13k31137
Thanks, appreciate the help!
– Gargoyle
Nov 20 '18 at 21:40
add a comment |
Thanks, appreciate the help!
– Gargoyle
Nov 20 '18 at 21:40
Thanks, appreciate the help!
– Gargoyle
Nov 20 '18 at 21:40
Thanks, appreciate the help!
– Gargoyle
Nov 20 '18 at 21:40
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53400565%2fangular-reactive-form-validation-with-dynamically-named-controls%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Is
workLeft
some sort of aFormArray
? If not, I recommend it to be one. That way you can create aget
ter on your Component Class and use theat
API on aFormArray
to get the relevantFormControl
/FormGroup
– SiddAjmera
Nov 20 '18 at 19:53
No, it's just an array of objects that was returned from an http webservice. But it's not a class variable, it's just created in the call that generates the form data.
– Gargoyle
Nov 20 '18 at 19:54
I'm not sure how your comment helps though as I'm asking about how to deal with it in the HTML itself, and I specifically mentioned not wanting to use a FormArray.
– Gargoyle
Nov 20 '18 at 19:58
1
That's because
FormArray
is something that is generally used in such scenarios. You want to show validation errors for each item inworkLeft
and it again is a form control. Also, I don't think you will need to keep any mapping to track the index and the form control anywhere. That's not how it works.– SiddAjmera
Nov 20 '18 at 20:02
OK, if it's the right way so be it. Can you show me what the div's *ngIf should look like please?
– Gargoyle
Nov 20 '18 at 20:03