我正在尝试使用Angular Material中的表单字段。
到目前为止我的代码:
app.module.ts:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatToolbarModule, MatFormFieldModule, MatButtonModule, MatCardModule, MatMenuModule, MatIconModule } from '@angular/material';
@NgModule({
declarations: [
AppComponent,
LoginComponent
],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
HttpModule,
BrowserAnimationsModule,
MatToolbarModule,
MatFormFieldModule,
MatButtonModule,
MatCardModule,
MatMenuModule,
MatIconModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
login.component.ts:
import { Component, OnInit } from '@angular/core';
import { usuario } from "../_modelos/usuario.model";
import {FormBuilder, FormGroup, FormControl, Validators} from '@angular/forms';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
email = new FormControl('', [Validators.required, Validators.email]);
getErrorMessage() {
return this.email.hasError('required') ? 'You must enter a value' :
this.email.hasError('email') ? 'Not a valid email' :
'';
}
constructor() {}
ngOnInit() {}
}
login.component.html:
<mat-toolbar color="primary">
<span>Sign in</span>
<span class="example-spacer"></span>
<img width="200" src="../assets/Logo_2.png">
</mat-toolbar>
<div class="example-container">
<mat-form-field>
<input matInput placeholder="Enter your email" [formControl]="email" required>
<mat-error *ngIf="email.invalid">{{getErrorMessage()}}</mat-error>
</mat-form-field>
</div>
login.component.css:
.example-spacer {
flex: 1 1 auto;
}
.example-container {
display: flex;
flex-direction: column;
}
.example-container > * {
width: 100%;
}
我从Angular Material的官方网站获得了代码。