How to put in value for an input with ngmodel selectmode?

Issue

I have two inputs with the same ngmodel:

<input type="text" placeholder="Time Range To:"
               [(ngModel)]="timeRange"
               [selectMode]="'rangeTo'"
               >

<input type="text" placeholder="Time Range To:"
               [(ngModel)]="timeRange"
               [selectMode]="'rangeFrom'"
               >

in my ts file, i use

public timeRange: Date[];

Retrieving the data is no problem by using this.timeRange[0] for example, but I want to put in a value with a button click and when i use this.timeRange[0], I get the following error:

ERROR TypeError: Cannot set property '0' of undefined

In my function I try to do this:

this.timeRange[0] = new Date(...);

How can I put in a value for the rangeTo and rangeFrom inputs?

Solution

Instead of using same variable to two input tags, just create an Object of timeRange and add from, to Dates according to your requirement.

<input type="text" placeholder="Time Range To:" [(ngModel)]="timeRange.to">

<input type="text" placeholder="Time Range To:" [(ngModel)]="timeRange.from">

in component.ts

use interface or an Object type to create variable, I am using interface here

timeRange = new timeRange();

//adding and retrieving is now simple with this

export interface timeRange {
  to?: Date();
  from?: Date();
}

Answered By – Ganesh

Answer Checked By – Marilyn (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.