📅  最后修改于: 2023-12-03 14:44:09.841000             🧑  作者: Mango
In this guide, we'll cover how to use the mat-input
component with datetime-local
input type and implement it in a TypeScript project.
First, we need to create a new Angular project using the Angular CLI.
ng new my-project --routing=false --style=scss
cd my-project
ng add @angular/material
Next, we need to import MatInputModule
and FormsModule
in our app module.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { MatInputModule } from '@angular/material/input';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, FormsModule, MatInputModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Now that we have set up our project, we can start using mat-input
with datetime-local
input type in our templates.
<mat-form-field>
<input matInput type="datetime-local" [(ngModel)]="date">
</mat-form-field>
In our component, we can create a date
variable to store the date selected by the user.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<mat-form-field>
<input matInput type="datetime-local" [(ngModel)]="date">
</mat-form-field>
`,
styles: []
})
export class AppComponent {
date: string;
}
If we want to pre-populate the datetime-local
input with the current date and time, we can use the Date
object in TypeScript.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<mat-form-field>
<input matInput type="datetime-local" [value]="nowToString()" [(ngModel)]="date">
</mat-form-field>
`,
styles: []
})
export class AppComponent {
date: string;
nowToString(): string {
const now = new Date();
return now.toISOString().slice(0, 16);
}
}
Here, we created a nowToString
method that returns the current date and time in YYYY-MM-DDTHH:mm
format, which is required by the datetime-local
input type.
We have successfully implemented mat-input
with datetime-local
input type in our TypeScript project. We learned how to pre-populate the input with the current date and time, and how to use the Date
object in TypeScript to format the date string.