Issue
In Angular-12, I am working on dynamic input formarray:
JSON:
{
"message": "Grading Successfully Retrieved.",
"error": false,
"code": 200,
"results": {
"gradings": [
{
"id": 3,
"grade": "TT",
"classification": "Test A",
},
{
"id": 4,
"grade": "MM",
"classification": "Test B"
}
]
}
}
interface:
export interface IPgss {
pgss: IPgs[];
}
export interface IPgs {
id?: number;
grade?: string;
classification?: string;
}
export class PgsResponse {
results!: { grading: IPgs[]; };
}
export interface Results { // random name
pgs: IPgs[];
}
service:
import { IPgs, PgsResponse } from 'src/app/models/pgs.model';
getPgsById(id: number): Observable<PgsResponse> {
return this.http.get<PgsResponse>(this.api.baseURL + 'pgs/fetchbyid/' + id, this.httpOptions);
}
component:
import { IPgs, PgsResponse } from 'src/app/models/pgs.model';
import { PgsService } from 'src/app/services/pgs.service';
pgs!: IPgs;
gradingdata!: IPgs[];
gradingInfoForm!: FormGroup;
data: any;
_id!: number;
constructor(
private fb: FormBuilder,
private pgsService: PgsService,
private router: Router,
private route: ActivatedRoute,
private store: Store<AppState>
) { }
ngOnInit(): void {
this._id = this.route.snapshot.params['id'];
}
loadGradingById() {
this.pgsService
.getGradingSetupById(this._id)
.subscribe((data: PgsResponse) => {
this.gradingdata = data.results.grading;
this.gradingInfoForm.setControl(
'gradings',
this.SetExistingGradings(this.gradingdata || [])
);
});
}
SetExistingGradings(gradingSets: IPgs[]): FormArray {
const formarray = new FormArray([]);
gradingSets.forEach(c => {
formarray.push(this.fb.group({
grade: c.grade,
classification: c.classification,
}));
});
return formarray;
}
I am trying to load and display the formarray data before update.
I got this error:
ERROR TypeError: gradingSets.forEach is not a function at GradingEditComponent.SetExistingGradings
With this highlighted:
gradingSets.forEach(c => {
and
this.SetExistingGradings(this.gradingdata || [])
How do I resolve this?
Thanks
Solution
this.SetExistingGradings(this.pgs || [])
use this.pgs
which is of type IPgs;
. It's not a IPgs[]
.
In your component, you have to change the type of
pgs!: IPgs;
to
pgs!: IPgs[];
Beside, your grading
in
export class PgsResponse {
results!: { grading: IPgs; };
}
is IPgs
and not IPgs[]
. So this.pgs = data.results.grading;
can't be of type IPgs[]
.
You should change your grading
type to IPgs[]
(if it matches your observable response from getGradingSetupById
) otherwise you'll have to look for a different solution to correctly type this.pgs
.
Answered By - Pilpo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.