Issue with the mat-datepicker in a loop

1.4k views Asked by At

I am learning the angularjs and am pretty new to it. I am trying to create 5 mat-datepicker components on the GUI using ngFor in the following manner (after a lot of online search)

<div fxLayout="row" fxFlex=20 fxLayoutAlign="center center" fxLayoutGap="35px">
            <mat-form-field fxFlex=20 appearance="outline" *ngFor="let pay of loanDetails.paymentOptions; index as i;">
                <mat-label>Start Date</mat-label>
                <input matInput [matDatepicker]="i" placeholder="Start date" [(ngModel)]="pay.paymentDate" (dateChange)="getLoanOutputData()">
                <mat-datepicker-toggle matSuffix [for]="i"></mat-datepicker-toggle>
                <mat-datepicker #i></mat-datepicker>
            </mat-form-field>
</div>

However, this does not seem to be working (meaning, the calendar was not opening when I am clicking on the calendar icon) and there a few exceptions being thrown.

Error on the loading of the page: enter image description here

And when clicking on the calendar icon, I am getting the below error: enter image description here

This is the structure of my loanDetails in the ts file

loanDetails = {
        principal: 100000,
        interestRate: 9.5,
        tenure: 5,
        startDate: new Date(),
        paymentOptions: [this.oneTimePay, this.yearlyPay, this.halfYearlyPay, this.quarterlyPay, this.monthlyPay]
    };

oneTimePay = {
        paymentType: "OneTime Payment",
        paymentDate: new Date(),
        paymentAmt: 0
    }

All the other "pays" like monthlyPay etc. follow the same pattern as of the oneTimePay

Please help me in understanding where it is going wrong.

1

There are 1 answers

3
Eliseo On BEST ANSWER

Really you are working with Angular (not Angularjs). Well, in a *ngFor you has not take care about the "template reference variable" name, you should use the same (you can not use "i" because Angular has two variables "i" -the variable of the loop and the template reference-

       <mat-form-field fxFlex=20 appearance="outline" 
         *ngFor="let pay of loanDetails.paymentOptions; index as i;">
            <mat-label>Start Date</mat-label>
             <!--see that use always 'picker'-->
            <input matInput [matDatepicker]="picker" placeholder="Start date" [(ngModel)]="pay.paymentDate" (dateChange)="getLoanOutputData()">
            <!--again 'picker'-->
            <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
            <!--and again 'picker'-->
            <mat-datepicker #picker></mat-datepicker>
        </mat-form-field>