Angular2 dynamic names for local variables that can be used for validation

I have multiple input fields that need to be validated and it works fine with my custom component error-msg

when I assign template local variables ( #requireSomeProperty1

) and validate them ( *ngIf="requireSomeProperty1.errors"

)

<input type="hidden" [(ngModel)]="activeItem.SomeProperty1" name="SomeProperty1" #requireSomeProperty1="ngModel" [required]="someConditions1"/>
<error-msg *ngIf="requireSomeProperty1.errors" message="Property1 is required"></error-msg>

<input type="hidden" [(ngModel)]="activeItem.SomeProperty2" name="SomeProperty2" #requireSomeProperty2="ngModel" [required]="someConditions2"/>
<error-msg *ngIf="requireSomeProperty2.errors" message="Property2 is required"></error-msg>

      

Now instead of hardcoding them into an html template, I need to load them from the database. Everything works fine, but I'm not sure how to achieve error checking / validation when generated with *ngFor

.

I tried this, but I had parsing errors:

<div *ngFor="let item of itemsFromDB; index as i">
    <input type="hidden" [(ngModel)]="activeItem[item.SomePropertyName]" [name]="item.SomePropertyName" #require_{{item.SomePropertyName}}="ngModel" [required]="item.SomeConditions">
    <error-msg *ngIf="require_{{item.SomePropertyName}}.errors" [message]="item.ErrorMessage"></error-msg>
</div>  

      

I also tried this, but I also got errors:

<div *ngFor="let item of itemsFromDB; index as i">
    <input type="hidden" [(ngModel)]="activeItem[item.SomePropertyName]" [name]="item.SomePropertyName" #require_item.SomePropertyName="ngModel" [required]="item.SomeConditions">
    <error-msg *ngIf="require_item.SomePropertyName.errors" [message]="item.ErrorMessage"></error-msg>
</div>

      

I tried this too and I didn't get any errors but nothing happened:

<div *ngFor="let item of itemsFromDB; index as i">
    <input type="hidden" [(ngModel)]="activeItem[item.SomePropertyName]" [name]="item.SomePropertyName" #require+item.SomePropertyName="ngModel" [required]="item.SomeConditions">
    <error-msg *ngIf="require+item.SomePropertyName.errors" [message]="item.ErrorMessage"></error-msg>
</div>

      

So what am I missing? Or am I trying to do the impossible here?

+3


source to share





All Articles