I have Angular form that is built with help of FormBuilder.
Form contains a FormArray which has as many fields as user wants. I've set validator for fields
this.fb.array([this.fb.control('', Validators.required)])
and for each new push
validator is the same.
The problem is that I don't know how to access a specific field's isValid
property since they are bound with FormControl
via [formControlName]="index"
.
I've tried to do it that way, but it doesn't seem to work
<div *ngIf="array.at(index).invalid" class="alert alert-danger p-2">
</div>
Where array
is a formArray.controls
passed from a parent.
Update #1
There is a case https://stackblitz.com/edit/angular-7ppkoh
You Should use form controls to achieve that sharply.
I don't really think this would be possible completely on the template. That's because to access the FormArray's control's state in your template, you'll have to access
this.formGroup.get('features').controls[i].invalid
. But sinceget
returns an instance of typeAbstractControl
, you won't have access to thecontrols
array on it. For that, you'll have to typecast whatever is returned fromthis.formGroup.get('features')
into aFormArray
. And I don't really think that would be possible on the template.You'll have to create a method in your class that would return the validity of the control based on the index.
So if we continue to refer to your stackblitz eg, here's how:
And in your class:
UPDATE
A few months back I realized that calling a method in one of the data-binding syntaxes(i.e. String Interpolation -
{{ ... }}
, Property Binding -[propertyName]="methodName()"
, or Attribute Binding -[class.class-name]="methodName()"
OR[style.styleName]="methodName()"
) is extremely costly as far as performance is concerned.So, you should do it using:
Instead of:
If you wanna know more about it, I highly recommend you to check this thread out:
Hope this helps :)
I have this example in angular 8.
In your template when you do this.
That item object in the ngFor will give you access to the form control. all you need to do to get the array form errors is
item.get('percentage').hasError('required')
In the ngFor statement, you are defining the variable "feature" to use for each control of the form array.
You can use that variable to get the invalid status of that control.
Here is the Stackblitz
Additionally
You don't need the required attribute in the HTML when you are using reactive forms.
So this
Can be
The FormGroup class has a get method which returns the abstractControl for the given key. The one you use in formControlName.
Here the links for both Api docs:
AbstractControl
FormGroup
As above answer using
let you validate all elements inside that controlat once.
However if you want to validate a specific element can you following code:
Note: I'm using feature not features