1、在APPModule.ts文件配置
import { browserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core';import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { FormsModule } from '@angular/forms'; import { ReactiveFormsModule } from '@angular/forms'; import { ReactiveFormComponent } from './reactive-form/reactive-form.component'; @NgModule({ declarations: [ AppComponent, ReactiveFormComponent ], imports: [ browserModule, AppRoutingModule, FormsModule, ReactiveFormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
2、html文件
<form [formGroup]="fg"> <label for="username">用户名:</label> <input type="text" id="username" formControlName="username" required> <!-- 这里的username关联的是从后台FormGroup里取出的FormControl对象 --> <div *ngIf="username.invalid && (username.dirty||username.touched)"> <div *ngIf="username.errors.required"> 用户名是必填项 </div> <div *ngIf="username.errors.minlength"> 用户名最小长度是5 </div> </div> </form> 3、ts文件 import { Component, OnInit } from '@angular/core'; import { FormControl ,FormGroup,Validators} from '@angular/forms';@Component({ selector: 'app-reactive-form', templateUrl: './reactive-form.component.html', styleUrls: ['./reactive-form.component.css'] }) export class ReactiveFormComponent implements OnInit { public fg:FormGroup; constructor() { }
ngOnInit() { this.validatorGroup(); } validatorGroup(){ this.fg=new FormGroup({ username:new FormControl('',[Validators.required,Validators.minLength(5)]), }); } //返回FormGroup里的FormControl对象 get username(){ return this.fg.get('username'); } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。