Angular 4 Reactive Forms切换隐藏表单元素的验证

前端之家收集整理的这篇文章主要介绍了Angular 4 Reactive Forms切换隐藏表单元素的验证前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个反应形式,在负载时不需要任何字段.如果选择了一个选项,将其他表单元素添加到formGroup中,则所有新显示的字段都是必需的.
如果昵称字段被隐藏,那么您应该能够提交表格.如果显示昵称,则需要昵称字段,并且在昵称字段已满之前禁用提交按钮.
这是我想要做的一个例子.

我的问题是,一旦显示/隐藏表单元素,如何启用/禁用验证?

App.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule,ReactiveFormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';

@NgModule({
  imports:      [ BrowserModule,FormsModule,ReactiveFormsModule ],declarations: [ AppComponent,HelloComponent ],bootstrap:    [ AppComponent ]
})
export class AppModule { }

App.component.ts

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

@Component({
  selector: 'my-app',templateUrl: './app.component.html',styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit  {
  name = 'My Reactive Form';

  constructor(
    private fb: FormBuilder
  ) {}

  myForm: FormGroup;
  showNick: boolean = false;

  ngOnInit() {
    this.myForm = this.fb.group({
      'firstName': new FormControl(),'nickName': new FormControl('',Validators.required),'lastName': new FormControl()
    })
  }

  toggleNick() {
    this.showNick = !this.showNick;
  }
}

app.component.html

<form [formGroup]="myForm">
  <div class="my-Box">
    <label>
      First Name
      <input type="text" formControlName="firstName">
    </label>
  </div>
  <div class="my-Box nickname">
    Nickname? &nbsp; <a (click)="toggleNick()">yes / no</a>
  </div>
  <div class="my-Box" *ngIf="showNick">
    <label>
      Nickname
      <input type="text" formControlName="nickName">
      <span class="validation-message" *ngIf="!myForm.controls['nickName'].valid && myForm.controls['nickName'].dirty">
    This field is invalid
  </span>
    </label>
  </div>
  <div class="my-Box">
    <label>
      Last Name
      <input type="text" formControlName="lastName">
    </label>
  </div>
  <button [disabled]="myForm.invalid">Submit</button>
</form>

解决方法

在我的申请中,我有类似的要求.如果用户要求通过文本通知,则需要电话.否则电话号码是可选的.

我写了这个方法

setNotification(notifyVia: string): void {
    const phoneControl = this.customerForm.get('phone');
    if (notifyVia === 'text') {
        phoneControl.setValidators(Validators.required);
    } else {
        phoneControl.clearValidators();
    }
    phoneControl.updateValueAndValidity();
}

它是从这个代码调用的,它位于ngOnInit中:

this.customerForm.get('notification').valueChanges
                     .subscribe(value => this.setNotification(value));

如果用户更改了通知字段(单选按钮),则会调用传入值的setNotification方法.如果值是’text’通知,则会将手机的验证设置为required.

否则它会清除手机字段的验证.

然后它必须调用updateValueAndValidity以使用此新验证更新表单信息.

猜你在找的Angularjs相关文章