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
I suggest using
FormArrayfor this. WithFormArray, here's how your implementation is going to look like:For the Component Class:
And in the template:
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.