-1

I'm new to angular, but I need to assign a date to a html input of type date when loading the page.

I noticed that if you change the input type from date to text, the value is assigned to the input, but leave as date the value is not assigned.

Someone would know where I'm going wrong.

Follow me code.

HTML

<input class="form-control" 
       type="date" 
       maxlength="10" 
       placeholder="dd/mm/yyyy"
       [(ngModel)]="carFilter.dataInicial"  
       (ngModelChange)="onDateChangeFim($event)"    
        min="{{auxFimMinDate}}"
        max="{{auxFimMaxDate}}">

Component Example

export class CarComponent implements AfterViewInit, OnInit {

    carFilter : CarModel;
    auxInMaxDate: Date  = new Date("2099-12-30");
    auxFimMinDate: Date  = new Date("1900-01-01");


    ngOnInit(): void {

        this.carFilter  = new CarModel();
        const data = new Date();        
        this.carFilter.dataInicial = data;

    }
}

Model Example

export class CarModel {

    offSet : number;
    dataInicial : Date;
    dataFinal : Date;

    constructor(
                offSet:number,
                dataInicial : Date,
                dataFinal : Date
                ){

        this.offSet = offSet;
        this.dataInicial = dataInicial;
        this.dataFinal = dataFinal;     

    }
}

Image input

enter image description here

Console Google Chrome

enter image description here

1

2 Answers 2

1

I was able to solve the problem by assigning my ngModel | date: 'yyyy-MM-dd'. I have to study why it worked that way. If anyone wants to comment or suggest something better I thank you. Thanks to all who helped @Samy Sammour and @Dmitriy Snitko

<input class="form-control" 
   type="date" 
   maxlength="10" 
   placeholder="dd/mm/yyyy"
   [ngModel]="carFilter.dataInicial | date:'yyyy-MM-dd'"  
   (ngModelChange)="onDateChangeFim($event)"    
    [min]="auxFimMinDate"
    [max]="auxFimMaxDate">
Sign up to request clarification or add additional context in comments.

Comments

0

The variable date should be an object from Date. not just a string.

So instead, try to add a real object:

this.carFilter  = new CarModel();
var data = new Date('10/09/2018');        
this.carFilter.dataInicial = data;

<input type="date" [(ngModel)]="carFilter.dataInicial" />

2 Comments

Thanks for the answer Samy Sammour, I did just that way, but the input does not render the value assigned in the component. I added a componet image to my question after changing my code as per your comment.
Try to use [value]="carFilter.dataInicial" instead of [(ngModel)]

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.