i have an <input type="date">
which i want to be filled when the user enters the route. By visiting the site the input field should already be the actual date.
So i think ngOnInit()
should be what i need. But what do i have to do to have the actual date filled in as a value to the input field, when the user enters the route?
I already tried to achive this by searching the web but only found some old solutions for angularjs although i'm using angular 5 which is not compareable with angularjs. The postings i found all pointed to the scope which is no longer existent.
The Documentation for ngOnInit
also does not help me :/
HTML
<div class="form-group">
<label>Eingangsdatum</label>
<input type="date" [(ngModel)]="dateArrival" id="dateArrivalPicker" value="" name="dateArrival" class="form-control">
</div>
Compontent
@Component({
selector: 'app-terminals-create',
templateUrl: './terminals-create.component.html',
styleUrls: ['./terminals-create.component.css']
})
export class TerminalsCreateComponent implements OnInit {
type: String;
serial: String;
layout: String;
dateArrival: Date;
activated: Boolean;
setup: String;
firmware: String;
installedAt: String;
createdBy: String;
createdDate: Date;
lastModified: Date;
lastModifiedBy: String;
notes: String;
macAddress: String;
constructor(
private validateService: ValidateService,
private flashMessage: FlashMessagesService,
private authService: AuthService,
private router: Router
) { }
ngOnInit() {}
}
If i do like briosheje wrote in his comments it works, his answer doesn't :/. And there is one more thing... by using his comment i get two big errors inside my console:
Error: If ngModel is used within a form tag, either the name attribute must be set or the form
control must be defined as 'standalone' in ngModelOptions.
Example 1: <input [(ngModel)]="person.firstName" name="first">
Example 2: <input [(ngModel)]="person.firstName" [ngModelOptions]="{standalone: true}">
If i now give a name to my <input type="date" [ngModel]="todaysDate | date:'dd-MM-yyyy'" (ngModelChange)="todaysDate = $event" [value]="todaysDate | date:'yyyy-MM-dd'">
the function of filling this field with the acutal date is gone and only TT.MM.YYYY stands there. What can i do?
It should be enough to add:
ngOnInit() {
this.dateArrival = new Date();
}
and change your HTML so that it will handle by itself the date to string and vice-versa, like suggested in this plunker (taken from another SO post): plnkr.co/edit/s5OMg2olU2yHI246nJOG?p=preview
<input type="date" [ngModel] ="dateArrival | date:'yyyy-MM-dd'" (ngModelChange)="dateArrival = $event">
the ngModelChange
will trigger the change automatically and will handle the date convertion aswell. The NgModel
, instead, will directly display the date through the date pipe