Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why template reference variable using ngModel is undefined inside a for-loop?

I'am trying to get a DOM element in HTML template to disable/enable a form-button based on input value and using ngModel:#Custom_FirstName="ngModel". The input is a custom field in separated component.

My issue is that the element Custom_FirstName is always undefined and I found out that it has to do with the For Loop ngFor. When I remove ngFor, The error is fixed. But this would not solve my issue because I need the for-loop as the user can add more than one input-text and user with firstName dynamically.

Code:

<div *ngFor="let el of users.departments.admins; let i=index; trackBy: trackByFn"
    <input-text [name]="'firstanme'"                                                             
                [(ngModel)]="el.firstName"                                                          
                [ngModelOptions]="{standalone: true}"                                                      
                [readonly]="false"                                                           
                [required]="true"
                labelText="First Name"
                #Custom_FirstName="ngModel">
    </input-text>
</div>

Button:

<button [disabled]="!Custom_FirstName.value || ....>

I have been checking the official Doc, but I was not able to find the fix for that. Any hint how work around this issue?

like image 466
k.vincent Avatar asked Dec 04 '25 08:12

k.vincent


1 Answers

Official documentation says:

The scope of a reference variable is the entire template. So, don't define the same variable name more than once in the same template as the runtime value will be unpredictable.

Since you already have bound input with data just track the data. Add to your component:

hasEmptyValue() {
    return users.departments.admins
        .some(admin => !admin.firstName || admin.firstName.length===0);
}

And make changes in template:

<button [disabled]="hasEmptyValue() || ....>
like image 58
Ken Bekov Avatar answered Dec 06 '25 23:12

Ken Bekov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!