zoukankan      html  css  js  c++  java
  • 响应式表单验证示例

    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');
      }
    }
     
  • 相关阅读:
    利用Selenium自动化web测试
    【译】.NET中六个重要的概念:栈、堆、值类型、引用类型、装箱和拆箱
    SlickGrid example 8:折线图
    SlickGrid example 7:鼠标事件
    SlickGrid example 6:Ajax加载
    SlickGrid example 5:带子项的展开收缩
    SlickGrid example 4: 过滤
    CentOS下配置iptables防火墙 linux NAT(iptables)配置
    ntp server
    parted
  • 原文地址:https://www.cnblogs.com/kukai/p/12113018.html
Copyright © 2011-2022 走看看