美文网首页
Angular--使用事件和表单(2)

Angular--使用事件和表单(2)

作者: 我是小布丁 | 来源:发表于2020-11-15 19:06 被阅读0次

1、简单的表单

class Product {
  constructor(
    public name?: string, 
    public category?: string, 
    public price?: number
  ){ }
}

@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.css']
})
export class FormComponent  {
  newProduct = new Product();
  constructor() { }
}
<div>
    JSONStringify: {{newProduct | json}}
</div>

<div>
    <label>Name:</label>
    <input [(ngModel)]="newProduct.name"/>
</div>
<div>
    <label>Category:</label>
    <input [(ngModel)]="newProduct.category"/>
</div>
<div>
    <label>price:</label>
    <input [(ngModel)]="newProduct.price"/>
</div>

<button nz-button nzType="primary">Primary</button>

使用ngModel将元素和newProduct对象模型进行绑定

2、添加表单校验

使用HTML元素和属性来定义构成表单的各个域并添加约束校验

JSONStringify: {{newProduct | json}}

<form (ngSubmit)="onSubmit(form)" #form="ngForm" novalidate>
    <div>
        <label>Name:</label>
        <input 
            [(ngModel)]="newProduct.name" 
            name="name" 
            required
            minlength="5"
            pattern="^[a-zA-Z ]+$"
            #name="ngModel"
        />
        <ul *ngIf="name.dirty && name.invalid">
            <li *ngIf="name.errors.required">
                这个是必填项
            </li>
            <li *ngIf="name.errors.minlength">
                至少输入{{name.errors.minlength.requiredLength}}
            </li>
            <li *ngIf="name.errors.pattern">
                只能输入{{name.errors.pattern.requiredPattern}}字符
            </li>
        </ul>
    </div>
    <div>
        <label>Category:</label>
        <input [(ngModel)]="newProduct.category" name="category"/>
    </div>
    <div>
        <label>price:</label>
        <input [(ngModel)]="newProduct.price" name="price"/>
    </div>
    <button type="submit" nz-button nzType="primary">Primary</button>
</form>
input{
    outline: none;
}
input.ng-dirty.ng-invalid{
    border: 2px solid #ff0000;
}
input.ng-dirty.ng-valid{
    border: 2px solid #6bc502;
}
image.png

input元素和form元素加入css类提供了有关验证状态的详细信息,共有3种验证类。

  • ng-dirty 和 ng-pristine
  • ng-valid 和 ng-invalid
  • ng-touched 和 ng-untouched

这里使用#name="ngModel"来获取访问器状态。错误信息属性,

  • xxx.errors.minlength.requiredLength
  • xxx.errors.minlength.actualLength
  • xxx.errors.pattern.requiredPattern
  • xxx.errors.pattern.actualValue

3、基于模型的表单

基于模型的表单功能在一个名的ReactiveFormsModule的模块中定义

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, NgForm, Validators } from '@angular/forms';

class ProductFormControl extends FormControl{
  label: string;
  modelProperty: string;
  constructor(
    label: string,
    property: string,
    value: any,
    validattor: any
  ){
    super(value, validattor);
    this.label = label;
    this.modelProperty = property;
  }
}

@Component({
  selector: 'app-form2',
  templateUrl: './form3.component.html',
  styleUrls: ['./form2.component.css']
})
export class Form2Component implements OnInit {
  formGroup: FormGroup;
  constructor(public fb: FormBuilder) {
    this.formGroup = this.fb.group({
      name: new ProductFormControl('Name','name', '', [
        Validators.required,
        Validators.minLength(5),
        Validators.pattern("^[a-zA-Z ]+$")
      ]),
      category: new ProductFormControl('Category','category', '', [Validators.required]),
      price:  new ProductFormControl('Price','price', '', [
        Validators.pattern("^[\\d]+$")
      ]),
    });
    console.log(this.formGroup.get('name'))
  }

  ngOnInit() {}
  onSubmit(){}
  getControls(){
    return Object.keys(this.formGroup.controls).map(k => 
      this.formGroup.controls[k] as ProductFormControl
      );
  }
  getValidatorMsgs(control: FormControl){
    let message: string[] = [];
    if(control.errors){
      Object.keys(control.errors).forEach(errorName => {
        switch(errorName){
          case 'required':
            message.push('此项为必填');
            break;
          case 'minlength':
            message.push('最小长度为' + control.errors.minlength.requiredLength);
            break;
          case 'pattern':
            message.push('只能输入' + control.errors.pattern.requiredPattern);
            break;
          default:
            break;
        }
      })
    }
    return message;
  }
}
JSONStringify: {{ formGroup.getRawValue()| json}}

<form (ngSubmit)="onSubmit()" novalidate [formGroup]="formGroup">
    <div *ngFor="let control of getControls()">
        <label>{{control.label}}</label>
        <input 
            name="{{control.modelProperty}}" 
            formControlName="{{control.modelProperty}}"
        />
        <ul *ngIf="control.dirty && control.invalid">
            <li *ngFor="let error of getValidatorMsgs(control)">
                {{error}}
            </li>
        </ul>
    </div>
    <button type="submit" nz-button nzType="primary">Primary</button>
</form>

错误信息统一在getValidatorMsgs方法中处理。formGroup.controls是一个object所以使用getControls方法去获取所以的controls。

4、自定义校验规则

新增limit.formvalidator.ts文件

import { FormControl } from '@angular/forms';

export class LimitValidator{
    static Limit(limit: number){
        return (control: FormControl)=> {
            let val = Number(control.value);
            if(val != NaN && val > limit){
                return {limit: {limit, actualValue: val}}
            } else {
                return null;
            }
        }
    }
}
...
 price:  new ProductFormControl('Price','price', '', [
        Validators.pattern("^[\\d]+$"),
        LimitValidator.Limit(100)
      ]),
...

...
case 'limit':
   message.push('不能大于' + control.errors.limit.limit);
  break;
...

相关文章

  • Angular--使用事件和表单(2)

    1、简单的表单 使用ngModel将元素和newProduct对象模型进行绑定 2、添加表单校验 使用HTML元素...

  • Angular--使用事件和表单(1)

    1、简单的事件绑定 事件绑定 用于响应宿主元素发送的事件,即从模板中的元素流向应用程序的其余部分,并能够进行用户交...

  • js事件,表单事件、DOM0级和DOM2级事件区别、事件传递(事

    表单事件、DOM0级和DOM2级事件、事件传递、拖拽效果 一、表单事件 1、表单事件焦点事件:focus inpu...

  • 学习笔记四|事件处理

    事件类型 传统事件类型 表单事件 当提交表单和重置表单时, 元素会分别触发submit和reset事件。 当用户和...

  • 表单提交

    表单提交方式 使用submit提交 使用button提交表单 使用超链接提交 onclick:鼠标点击事件onch...

  • jQuery(事件)

    DOM事件 表单事件 键盘事件 事件的绑定和解绑 事件对象的使用 自定义事件

  • Day26-js3

    1、DOM操作 2、事件绑定和事件冒泡 3、小知识 3、正则对象 4、表单对象

  • v-model

    使用自定义事件的表单输入组件自定义事件可以用来创建自定义的表单输入组件,使用 v-model 来进行数据双向绑定。...

  • 表单提交中onSumbit和提交按钮的onClick事件

    onSubmit只能在表单上使用,提交表单前会触发。 onClick在按钮能控件上使用,用来触发点击事件。 在提交...

  • 事件处理--表单事件2

    文本框脚本 HTML5约束验证API 文本框脚本   在html中,有两种方式来表现文本框,一种是input单行文...

网友评论

      本文标题:Angular--使用事件和表单(2)

      本文链接:https://www.haomeiwen.com/subject/vwwnbktx.html