Angular响应式表单

本文详细介绍了Angular响应式表单的使用,包括响应式表单基础元件的引入、构建,如何创建FormGroup,对表单字段进行分组,更新表单值,使用内置验证器,优化提示信息,自定义表单规则,给FormGroup添加校验,动态获取FormControl的值,以及使用FormBuilder服务简化表单创建过程。
摘要由CSDN通过智能技术生成

Angular响应式表单

Angular响应式表单是建立在RxJS基础上,有很多接口是使用RxJs接口实现

一.响应式表单基础元件

1.项目引入
  • @angular/forms中引入ReactiveFormsModule
  • 响应式表单基础元件: FormControl [来自@angular/forms]
2.项目构建
  • 创建FormControl对象

    import { Component } from '@angular/core';
    import { FormControl } from '@angular/forms';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      user = new FormControl();
    }
    
  • 使用定义的对象

    <input type="text" [formControl]="user" />
    <div>
        {
        {user.value | json}}
    </div>
    
  • 效果:当在输入框输入内容时,会直接在页面中进行显示

3.组件中获取和更新控件的值
  • 可以通过监听FormControl的valueChanges方法获取对应值,也可以通过setValue方法设置对应值

    import { Component, OnInit } from '@angular/core';
    import { FormControl } from '@angular/forms';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit{
      user = new FormControl();
      ngOnInit() {
        // 由于FormControl的valueChanges方法返回的是Observable对象
        // 需要使用subscribe的方式进行监听
        this.user.valueChanges.subscribe((val)=>{
          console.log(val);
        });
      }
      changeUserName() {
        this.user.setValue('Jack'); //通过FormControl的setValue方法可以设置对应的值
      }
    }
    
  • 在模板中进行显示

    <input type="text" [formControl]="user"/>
    <button (click)="changeUserName()">Click</button>
    <div>
      {
        {user.value | json}}
    </div>
    

二.使用FormGroup创建表单

1.项目引入
  • @angular/forms中引入FormGroup和FormControl
2.实例代码
  • ts中定义FormGroup对象,并包含多个FormControl对象;声明onSubmit方法用于打印FormGroup中的数据信息

    import { Component, OnInit } from '@angular/core';
    import { FormGroup, FormControl } from '@angular/forms';
    @Component({
      selector: 'app-FormGroupTest',
      templateUrl: './FormGroupTest.component.html',
      styleUrls: ['./FormGroupTest.component.css']
    })
    export class FormGroupTestComponent {
      userInfo = new FormGroup({
        userName: new FormControl(),
        phone: new FormControl(),
        sex: new FormControl()
      });
      onSubmit() {
        console.log(this.userInfo.value);
      }
    }
    
  • html中使用[formGroup]绑定ts中的对象,通过angular自带的form标签的提交事件ngSubmit设置点击submit按钮时的触发事件

    <form [formGroup]="userInfo" (ngSubmit)="onSubmit()">
      <input type="text" formControlName="userName"/>
      <input type="text" formControlName="phone"/>
      
      <input type="radio" formControlName="sex" value="1"/><input type="radio" formControlName="sex" value="0"/><button type="submit">提交</button>
    </form>
    
  • 此时点击提交后打印的内容就是表单中实际值

3.对表单字段进行分组
  • 如果想声明嵌套表单,则可以通过FormGroup中嵌套FormGroup的方式进行实现

  • TypeScript中实现内容

    import { Component, OnInit } from '@angular/core';
    import { FormGroup, FormControl } from '@angular/forms';
    
    @Component({
      selector: 'app-FormGroupTest',
      templateUrl: './FormGroupTest.component.html',
      styleUrls: ['./FormGroupTest.component.css']
    })
    export class FormGroupTestComponent {
      userInfo = new FormGroup({
        userName: new FormControl(),
        phone: new FormControl(),
        sex: new FormControl(),
        pwd: new FormGroup({
          password: new FormControl(),
          confirmPassword: new FormControl()
        })
      });
      onSubmit() {
        console.log(this.userInfo.value);
      }
    }
    
  • Html中在form中添加form并设置属性名为formGroupName

    <form [formGroup]="userInfo" (ngSubmit)="onSubmit()">
      <input type="text" formControlName="userName"/>
      <input type="text" formControlName="phone"/>
      
      <input type="radio" formControlName="sex" value="1"/><input type="radio" formControlName="sex" value="0"/><form formGroupName="pwd">
        <input type="text" formControlName="password"/>
        <input type="text" formControlName="confirmPassword"/>
      </form>
    
      <button type="submit">提交</button>
    </form>
    
  • 输出内容为嵌套对象的形式

    {
        phone: "180411",
        pwd: {password: "123456", confirmPassword: "123456"},
        sex: "1",
        userName: "jack"
    }
    
4.更新表单中字段
  • 注意:如果使用FormGroup的方式声明表单,再使用form.setValue()方法时需要设置所有表单值,如设置不全则会进行报错

  • 更新表单指定字段方式一:使用form.patchValue(键值对象);方法设置表单中指定字段的值

  • 更新表单指定字段方式二:先使用form.get(键)获取formControl对象,再调用setValue方法:,如this.userInfo.get('userName').setValue('Jerry');

  • 实例代码

    • TypeScript

      import { Component, OnInit } from '@angular/core';
      import { FormGroup, FormControl } from '@angular/forms';
      @Component({
        selector: 'app-FormGroupTest',
        templateUrl: './FormGroupTest.component.html',
        styleUrls: ['./FormGroupTest.component.css']
      })
      export class FormGroupTestComponent {
        userInfo = new FormGroup({
          userName: new FormControl(),
          phone: new FormControl(),
          sex: new FormControl(),
          pwd: new FormGroup({
            password: new FormControl(),
            confirmPassword: new FormControl()
          })
        });
        onSubmit() {
          console.log(this.userInfo.value);
        }
        updateFormData() {
          // this.userIn
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值