I’m trying to generate form controls dynamically on click of a button in Angular v14 html template i generate it but i’m facing that error in console.
ERROR TypeError: feature_r5.get is not a function
at PostAdvComponent_div_40_Template
Html template code
<div id="features" class="tab-pane mytab-pane">
<div class="form-group">
<button type="button" class="btn btn-primary" (click)="addFeatureButtonClick()">Add</button>
</div>
<div formArrayName="features" *ngFor="let feature of advForm.get('features')?.value; let i = index">
<div attr.formGroupName="{{i}}">
<div class="form-group" [ngClass]="{'has-error' : feature.get('fName').invalid &&
feature.get('fName').touched}">
<div class="input-group">
<span class="input-group-prepend">
<label class="input-group-text"><strong>Features</strong></label>
</span>
<input type="text" id="{{'fName'+i}}" name="fName" class="form-control" placeholder="Features"
formControlName="fName"/>
</div>
<span class="help-block" *ngIf="feature.get('fName').errors.required &&
feature.get('fName').touched">
Feature is required
</span>
</div>
</div>
</div>
</div>
2
Answers
The error you’re encountering, ERROR TypeError: feature_r5.get is not a function, suggests that the feature object you’re using in your template doesn’t have a get function. This error typically occurs when you try to access a property or invoke a method on an undefined or null value.
In your template, you’re using feature.get(‘fName’) multiple times. The issue might be with the way you’re accessing the feature object within the *ngFor loop.
To fix this error, make sure that advForm.get(‘features’)?.value is not null or undefined. Additionally, ensure that each feature object within the loop is a FormGroup instance, as it should have a get method.
Here are a few steps you can take to troubleshoot and resolve the issue:
Verify that advForm.get(‘features’)?.value is properly populated with an array of FormGroup instances.
Make sure that feature within the *ngFor loop refers to a FormGroup object.
Double-check that the fName form control exists within each feature FormGroup.
Not iterate over the values (else when you change an input, Angular redraw and you loose the focus):
You need use a "getter"
and iterate over "controls"
formGroupName is not an attribute, else a directive, so
When manage fromGroup of formArray I like more use this structure
(the formArrayName outside the loop, the same tag in loop, the
formGroupName):
You need use the safe operator (see the ? before the dot) after the
.get else you have an error of "possible null or undefined"
Same before when you check errors.required