Form表单

具有数据收集、校验和提交功能的表单,包含复选框、单选框、输入框、下拉选择框等元素。

该组件需要与 Angular表单 结合使用,开发者根据需要可以自由选择 响应式表单模板驱动表单.

使用该组件前请确保您已经阅读并掌握了 Forms 的使用方式。

表单

我们提供了以下三种排列方式:

  • 水平排列:标签和表单控件水平排列;(默认)
  • 垂直排列:标签和表单控件上下垂直排列;
  • 行内排列:表单项水平行内排列。

表单项 nz-form-item

表单项用于区分表单中不同的区域,包含表单域和表单标签(可选)。

表单标签 nz-form-label

用于标示当前表单项的内容,可选。

表单域 nz-form-control

表单一定会包含表单域,表单域可以是输入控件,标准表单域,标签,下拉菜单,文本域等。

  1. <form nz-form>
  2. <nz-form-item>
  3. <nz-form-label [nzSpan]="6" nzFor="email">E-mail</nz-form-label>
  4. <nz-form-control [nzSpan]="14">
  5. <input nz-input name="email" type="email" id="email">
  6. </nz-form-control>
  7. </nz-form-item >
  8. </form>

单独引入此组件

想要了解更多关于单独引入组件的内容,可以在快速上手页面进行查看。

  1. import { NzFormModule } from 'ng-zorro-antd/form';

代码演示

Form表单 - 图1

水平登录栏

水平登录栏,常用在顶部导航栏中。

  1. import { Component, OnInit } from '@angular/core';
  2. import { FormBuilder, FormGroup, Validators } from '@angular/forms';
  3. @Component({
  4. selector: 'nz-demo-form-horizontal-login',
  5. template: `
  6. <form nz-form [nzLayout]="'inline'" [formGroup]="validateForm" (ngSubmit)="submitForm()">
  7. <nz-form-item>
  8. <nz-form-control nzErrorTip="Please input your username!">
  9. <nz-input-group nzPrefixIcon="user">
  10. <input formControlName="userName" nz-input placeholder="Username" />
  11. </nz-input-group>
  12. </nz-form-control>
  13. </nz-form-item>
  14. <nz-form-item>
  15. <nz-form-control nzErrorTip="Please input your Password!">
  16. <nz-input-group nzPrefixIcon="lock">
  17. <input formControlName="password" nz-input type="password" placeholder="Password" />
  18. </nz-input-group>
  19. </nz-form-control>
  20. </nz-form-item>
  21. <nz-form-item>
  22. <nz-form-control>
  23. <button nz-button nzType="primary" [disabled]="!validateForm.valid">Log in</button>
  24. </nz-form-control>
  25. </nz-form-item>
  26. </form>
  27. `
  28. })
  29. export class NzDemoFormHorizontalLoginComponent implements OnInit {
  30. validateForm: FormGroup;
  31. submitForm(): void {
  32. for (const i in this.validateForm.controls) {
  33. this.validateForm.controls[i].markAsDirty();
  34. this.validateForm.controls[i].updateValueAndValidity();
  35. }
  36. }
  37. constructor(private fb: FormBuilder) {}
  38. ngOnInit(): void {
  39. this.validateForm = this.fb.group({
  40. userName: [null, [Validators.required]],
  41. password: [null, [Validators.required]],
  42. remember: [true]
  43. });
  44. }
  45. }

Form表单 - 图2

登录框

普通的登录框,可以容纳更多的元素。

  1. import { Component, OnInit } from '@angular/core';
  2. import { FormBuilder, FormGroup, Validators } from '@angular/forms';
  3. @Component({
  4. selector: 'nz-demo-form-normal-login',
  5. template: `
  6. <form nz-form [formGroup]="validateForm" class="login-form" (ngSubmit)="submitForm()">
  7. <nz-form-item>
  8. <nz-form-control nzErrorTip="Please input your username!">
  9. <nz-input-group nzPrefixIcon="user">
  10. <input type="text" nz-input formControlName="userName" placeholder="Username" />
  11. </nz-input-group>
  12. </nz-form-control>
  13. </nz-form-item>
  14. <nz-form-item>
  15. <nz-form-control nzErrorTip="Please input your Password!">
  16. <nz-input-group nzPrefixIcon="lock">
  17. <input type="password" nz-input formControlName="password" placeholder="Password" />
  18. </nz-input-group>
  19. </nz-form-control>
  20. </nz-form-item>
  21. <nz-form-item>
  22. <nz-form-control>
  23. <label nz-checkbox formControlName="remember">
  24. <span>Remember me</span>
  25. </label>
  26. <a class="login-form-forgot" class="login-form-forgot">Forgot password</a>
  27. <button nz-button class="login-form-button" [nzType]="'primary'">Log in</button>
  28. Or
  29. <a>register now!</a>
  30. </nz-form-control>
  31. </nz-form-item>
  32. </form>
  33. `,
  34. styles: [
  35. `
  36. .login-form {
  37. max-width: 300px;
  38. }
  39. .login-form-forgot {
  40. float: right;
  41. }
  42. .login-form-button {
  43. width: 100%;
  44. }
  45. `
  46. ]
  47. })
  48. export class NzDemoFormNormalLoginComponent implements OnInit {
  49. validateForm: FormGroup;
  50. submitForm(): void {
  51. for (const i in this.validateForm.controls) {
  52. this.validateForm.controls[i].markAsDirty();
  53. this.validateForm.controls[i].updateValueAndValidity();
  54. }
  55. }
  56. constructor(private fb: FormBuilder) {}
  57. ngOnInit(): void {
  58. this.validateForm = this.fb.group({
  59. userName: [null, [Validators.required]],
  60. password: [null, [Validators.required]],
  61. remember: [true]
  62. });
  63. }
  64. }

Form表单 - 图3

注册新用户

用户填写必须的信息以注册新用户。

  1. import { Component, OnInit } from '@angular/core';
  2. import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
  3. @Component({
  4. selector: 'nz-demo-form-register',
  5. template: `
  6. <form nz-form [formGroup]="validateForm" (ngSubmit)="submitForm()">
  7. <nz-form-item>
  8. <nz-form-label [nzSm]="6" [nzXs]="24" nzRequired nzFor="email">E-mail</nz-form-label>
  9. <nz-form-control [nzSm]="14" [nzXs]="24" nzErrorTip="The input is not valid E-mail!">
  10. <input nz-input formControlName="email" id="email" />
  11. </nz-form-control>
  12. </nz-form-item>
  13. <nz-form-item>
  14. <nz-form-label [nzSm]="6" [nzXs]="24" nzFor="password" nzRequired>Password</nz-form-label>
  15. <nz-form-control [nzSm]="14" [nzXs]="24" nzErrorTip="Please input your password!">
  16. <input
  17. nz-input
  18. type="password"
  19. id="password"
  20. formControlName="password"
  21. (ngModelChange)="updateConfirmValidator()"
  22. />
  23. </nz-form-control>
  24. </nz-form-item>
  25. <nz-form-item>
  26. <nz-form-label [nzSm]="6" [nzXs]="24" nzFor="checkPassword" nzRequired>Confirm Password</nz-form-label>
  27. <nz-form-control [nzSm]="14" [nzXs]="24" [nzErrorTip]="errorTpl">
  28. <input nz-input type="password" formControlName="checkPassword" id="checkPassword" />
  29. <ng-template #errorTpl let-control>
  30. <ng-container *ngIf="control.hasError('required')">
  31. Please confirm your password!
  32. </ng-container>
  33. <ng-container *ngIf="control.hasError('confirm')">
  34. Two passwords that you enter is inconsistent!
  35. </ng-container>
  36. </ng-template>
  37. </nz-form-control>
  38. </nz-form-item>
  39. <nz-form-item>
  40. <nz-form-label [nzSm]="6" [nzXs]="24" nzFor="nickname" nzRequired>
  41. <span>
  42. Nickname
  43. <i
  44. nz-icon
  45. nz-tooltip
  46. nzTitle="What do you want other to call you"
  47. type="question-circle"
  48. nzTheme="outline"
  49. ></i>
  50. </span>
  51. </nz-form-label>
  52. <nz-form-control [nzSm]="14" [nzXs]="24" nzErrorTip="Please input your nickname!">
  53. <input nz-input id="nickname" formControlName="nickname" />
  54. </nz-form-control>
  55. </nz-form-item>
  56. <nz-form-item>
  57. <nz-form-label [nzSm]="6" [nzXs]="24" nzFor="phoneNumber" nzRequired>Phone Number</nz-form-label>
  58. <nz-form-control
  59. [nzSm]="14"
  60. [nzXs]="24"
  61. [nzValidateStatus]="validateForm.controls['phoneNumber']"
  62. nzErrorTip="Please input your phone number!"
  63. >
  64. <nz-input-group [nzAddOnBefore]="addOnBeforeTemplate">
  65. <ng-template #addOnBeforeTemplate>
  66. <nz-select formControlName="phoneNumberPrefix" class="phone-select">
  67. <nz-option nzLabel="+86" nzValue="+86"></nz-option>
  68. <nz-option nzLabel="+87" nzValue="+87"></nz-option>
  69. </nz-select>
  70. </ng-template>
  71. <input formControlName="phoneNumber" id="'phoneNumber'" nz-input />
  72. </nz-input-group>
  73. </nz-form-control>
  74. </nz-form-item>
  75. <nz-form-item>
  76. <nz-form-label [nzSm]="6" [nzXs]="24" nzFor="website" nzRequired>Website</nz-form-label>
  77. <nz-form-control [nzSm]="14" [nzXs]="24" nzErrorTip="Please input website!">
  78. <input nz-input id="website" formControlName="website" placeholder="website" />
  79. </nz-form-control>
  80. </nz-form-item>
  81. <nz-form-item>
  82. <nz-form-label [nzSm]="6" [nzXs]="24" nzFor="captcha" nzRequired>Captcha</nz-form-label>
  83. <nz-form-control
  84. [nzSm]="14"
  85. [nzXs]="24"
  86. nzErrorTip="Please input the captcha you got!"
  87. nzExtra="We must make sure that your are a human."
  88. >
  89. <div nz-row [nzGutter]="8">
  90. <div nz-col [nzSpan]="12">
  91. <input nz-input formControlName="captcha" id="captcha" />
  92. </div>
  93. <div nz-col [nzSpan]="12">
  94. <button nz-button (click)="getCaptcha($event)">Get captcha</button>
  95. </div>
  96. </div>
  97. </nz-form-control>
  98. </nz-form-item>
  99. <nz-form-item nz-row class="register-area">
  100. <nz-form-control [nzSpan]="14" [nzOffset]="6">
  101. <label nz-checkbox formControlName="agree">
  102. <span>I have read the <a>agreement</a></span>
  103. </label>
  104. </nz-form-control>
  105. </nz-form-item>
  106. <nz-form-item nz-row class="register-area">
  107. <nz-form-control [nzSpan]="14" [nzOffset]="6">
  108. <button nz-button nzType="primary">Register</button>
  109. </nz-form-control>
  110. </nz-form-item>
  111. </form>
  112. `,
  113. styles: [
  114. `
  115. [nz-form] {
  116. max-width: 600px;
  117. }
  118. .phone-select {
  119. width: 70px;
  120. }
  121. .register-are {
  122. margin-bottom: 8px;
  123. }
  124. `
  125. ]
  126. })
  127. export class NzDemoFormRegisterComponent implements OnInit {
  128. validateForm: FormGroup;
  129. submitForm(): void {
  130. for (const i in this.validateForm.controls) {
  131. this.validateForm.controls[i].markAsDirty();
  132. this.validateForm.controls[i].updateValueAndValidity();
  133. }
  134. }
  135. updateConfirmValidator(): void {
  136. /** wait for refresh value */
  137. Promise.resolve().then(() => this.validateForm.controls.checkPassword.updateValueAndValidity());
  138. }
  139. confirmationValidator = (control: FormControl): { [s: string]: boolean } => {
  140. if (!control.value) {
  141. return { required: true };
  142. } else if (control.value !== this.validateForm.controls.password.value) {
  143. return { confirm: true, error: true };
  144. }
  145. return {};
  146. };
  147. getCaptcha(e: MouseEvent): void {
  148. e.preventDefault();
  149. }
  150. constructor(private fb: FormBuilder) {}
  151. ngOnInit(): void {
  152. this.validateForm = this.fb.group({
  153. email: [null, [Validators.email, Validators.required]],
  154. password: [null, [Validators.required]],
  155. checkPassword: [null, [Validators.required, this.confirmationValidator]],
  156. nickname: [null, [Validators.required]],
  157. phoneNumberPrefix: ['+86'],
  158. phoneNumber: [null, [Validators.required]],
  159. website: [null, [Validators.required]],
  160. captcha: [null, [Validators.required]],
  161. agree: [false]
  162. });
  163. }
  164. }

Form表单 - 图4

高级搜索

三列栅格式的表单排列方式,常用于数据表格的高级搜索。

有部分定制的样式代码,由于输入标签长度不确定,需要根据具体情况自行调整。

  1. import { Component, OnInit } from '@angular/core';
  2. import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
  3. @Component({
  4. selector: 'nz-demo-form-advanced-search',
  5. template: `
  6. <form nz-form [formGroup]="validateForm" class="ant-advanced-search-form">
  7. <div nz-row [nzGutter]="24">
  8. <div nz-col [nzSpan]="8" *ngFor="let control of controlArray" [hidden]="!control.show">
  9. <nz-form-item nzFlex>
  10. <nz-form-label [nzFor]="'field' + control.index">Field {{ control.index }}</nz-form-label>
  11. <nz-form-control>
  12. <input
  13. nz-input
  14. placeholder="placeholder"
  15. [formControlName]="'field' + control.index"
  16. [attr.id]="'field' + control.index"
  17. />
  18. </nz-form-control>
  19. </nz-form-item>
  20. </div>
  21. </div>
  22. <div nz-row>
  23. <div nz-col [nzSpan]="24" class="search-area">
  24. <button nz-button [nzType]="'primary'">Search</button>
  25. <button nz-button (click)="resetForm()">Clear</button>
  26. <a class="collapse" (click)="toggleCollapse()">
  27. Collapse
  28. <i nz-icon [nzType]="isCollapse ? 'down' : 'up'"></i>
  29. </a>
  30. </div>
  31. </div>
  32. </form>
  33. <div class="search-result-list">
  34. Search Result List
  35. </div>
  36. `,
  37. styles: [
  38. `
  39. .ant-advanced-search-form {
  40. padding: 24px;
  41. background: #fbfbfb;
  42. border: 1px solid #d9d9d9;
  43. border-radius: 6px;
  44. }
  45. .search-result-list {
  46. margin-top: 16px;
  47. border: 1px dashed #e9e9e9;
  48. border-radius: 6px;
  49. background-color: #fafafa;
  50. min-height: 200px;
  51. text-align: center;
  52. padding-top: 80px;
  53. }
  54. [nz-form-label] {
  55. overflow: visible;
  56. }
  57. button {
  58. margin-left: 8px;
  59. }
  60. .collapse {
  61. margin-left: 8px;
  62. font-size: 12px;
  63. }
  64. .search-area {
  65. text-align: right;
  66. }
  67. `
  68. ]
  69. })
  70. export class NzDemoFormAdvancedSearchComponent implements OnInit {
  71. validateForm: FormGroup;
  72. controlArray: any[] = [];
  73. isCollapse = true;
  74. toggleCollapse(): void {
  75. this.isCollapse = !this.isCollapse;
  76. this.controlArray.forEach((c, index) => {
  77. c.show = this.isCollapse ? index < 6 : true;
  78. });
  79. }
  80. resetForm(): void {
  81. this.validateForm.reset();
  82. }
  83. constructor(private fb: FormBuilder) {}
  84. ngOnInit(): void {
  85. this.validateForm = this.fb.group({});
  86. for (let i = 0; i < 10; i++) {
  87. this.controlArray.push({ index: i, show: i < 6 });
  88. this.validateForm.addControl(`field${i}`, new FormControl());
  89. }
  90. }
  91. }

Form表单 - 图5

动态增减表单项

动态增加、减少表单项。

  1. import { Component, OnInit } from '@angular/core';
  2. import { AbstractControl, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
  3. @Component({
  4. selector: 'nz-demo-form-dynamic-form-item',
  5. template: `
  6. <form nz-form [formGroup]="validateForm" (ngSubmit)="submitForm()">
  7. <nz-form-item *ngFor="let control of listOfControl; let i = index">
  8. <nz-form-label [nzXs]="24" [nzSm]="4" *ngIf="i == 0" [nzFor]="control.controlInstance"
  9. >Passengers
  10. </nz-form-label>
  11. <nz-form-control
  12. [nzXs]="24"
  13. [nzSm]="20"
  14. [nzOffset]="i == 0 ? 0 : 4"
  15. nzErrorTip="Please input passenger's name or delete this field."
  16. >
  17. <input
  18. class="passenger-input"
  19. nz-input
  20. placeholder="placeholder"
  21. [attr.id]="control.id"
  22. [formControlName]="control.controlInstance"
  23. />
  24. <i nz-icon nzType="minus-circle-o" class="dynamic-delete-button" (click)="removeField(control, $event)"></i>
  25. </nz-form-control>
  26. </nz-form-item>
  27. <nz-form-item>
  28. <nz-form-control [nzXs]="{ span: 24, offset: 0 }" [nzSm]="{ span: 20, offset: 4 }">
  29. <button nz-button nzType="dashed" class="add-button" (click)="addField($event)">
  30. <i nz-icon nzType="plus"></i>
  31. Add field
  32. </button>
  33. </nz-form-control>
  34. </nz-form-item>
  35. <nz-form-item>
  36. <nz-form-control [nzXs]="{ span: 24, offset: 0 }" [nzSm]="{ span: 20, offset: 4 }">
  37. <button nz-button nzType="primary">Submit</button>
  38. </nz-form-control>
  39. </nz-form-item>
  40. </form>
  41. `,
  42. styles: [
  43. `
  44. .dynamic-delete-button {
  45. cursor: pointer;
  46. position: relative;
  47. top: 4px;
  48. font-size: 24px;
  49. color: #999;
  50. transition: all 0.3s;
  51. }
  52. .dynamic-delete-button:hover {
  53. color: #777;
  54. }
  55. .passenger-input {
  56. width: 60%;
  57. margin-right: 8px;
  58. }
  59. [nz-form] {
  60. max-width: 600px;
  61. }
  62. .add-button {
  63. width: 60%;
  64. }
  65. `
  66. ]
  67. })
  68. export class NzDemoFormDynamicFormItemComponent implements OnInit {
  69. validateForm: FormGroup;
  70. listOfControl: Array<{ id: number; controlInstance: string }> = [];
  71. addField(e?: MouseEvent): void {
  72. if (e) {
  73. e.preventDefault();
  74. }
  75. const id = this.listOfControl.length > 0 ? this.listOfControl[this.listOfControl.length - 1].id + 1 : 0;
  76. const control = {
  77. id,
  78. controlInstance: `passenger${id}`
  79. };
  80. const index = this.listOfControl.push(control);
  81. console.log(this.listOfControl[this.listOfControl.length - 1]);
  82. this.validateForm.addControl(
  83. this.listOfControl[index - 1].controlInstance,
  84. new FormControl(null, Validators.required)
  85. );
  86. }
  87. removeField(i: { id: number; controlInstance: string }, e: MouseEvent): void {
  88. e.preventDefault();
  89. if (this.listOfControl.length > 1) {
  90. const index = this.listOfControl.indexOf(i);
  91. this.listOfControl.splice(index, 1);
  92. console.log(this.listOfControl);
  93. this.validateForm.removeControl(i.controlInstance);
  94. }
  95. }
  96. getFormControl(name: string): AbstractControl {
  97. return this.validateForm.controls[name];
  98. }
  99. submitForm(): void {
  100. for (const i in this.validateForm.controls) {
  101. this.validateForm.controls[i].markAsDirty();
  102. this.validateForm.controls[i].updateValueAndValidity();
  103. }
  104. console.log(this.validateForm.value);
  105. }
  106. constructor(private fb: FormBuilder) {}
  107. ngOnInit(): void {
  108. this.validateForm = this.fb.group({});
  109. this.addField();
  110. }
  111. }

Form表单 - 图6

时间类控件

时间类组件的输入和输出类型均为 Date 类型,可以通过 date-fns 工具库进行进一步的处理。

  1. import { Component, OnInit } from '@angular/core';
  2. import { FormBuilder, FormGroup } from '@angular/forms';
  3. @Component({
  4. selector: 'nz-demo-form-time-related-controls',
  5. template: `
  6. <form nz-form [formGroup]="validateForm" (ngSubmit)="submitForm()">
  7. <nz-form-item>
  8. <nz-form-label [nzSm]="8" [nzXs]="24" nzRequired>DatePicker</nz-form-label>
  9. <nz-form-control [nzSm]="16" [nzXs]="24">
  10. <nz-date-picker formControlName="datePicker"></nz-date-picker>
  11. </nz-form-control>
  12. </nz-form-item>
  13. <nz-form-item>
  14. <nz-form-label [nzSm]="8" [nzXs]="24" nzRequired>DatePicker[ShowTime]</nz-form-label>
  15. <nz-form-control [nzSm]="16" [nzXs]="24">
  16. <nz-date-picker nzShowTime formControlName="datePickerTime"></nz-date-picker>
  17. </nz-form-control>
  18. </nz-form-item>
  19. <nz-form-item>
  20. <nz-form-label [nzSm]="8" [nzXs]="24" nzRequired>MonthPicker</nz-form-label>
  21. <nz-form-control [nzSm]="16" [nzXs]="24">
  22. <nz-month-picker formControlName="monthPicker"></nz-month-picker>
  23. </nz-form-control>
  24. </nz-form-item>
  25. <nz-form-item>
  26. <nz-form-label [nzSm]="8" [nzXs]="24" nzRequired>RangePicker</nz-form-label>
  27. <nz-form-control [nzSm]="16" [nzXs]="24">
  28. <nz-range-picker formControlName="rangePicker"></nz-range-picker>
  29. </nz-form-control>
  30. </nz-form-item>
  31. <nz-form-item>
  32. <nz-form-label [nzSm]="8" [nzXs]="24" nzRequired>RangePicker[showTime]</nz-form-label>
  33. <nz-form-control [nzSm]="16" [nzXs]="24">
  34. <nz-range-picker nzShowTime formControlName="rangePickerTime"></nz-range-picker>
  35. </nz-form-control>
  36. </nz-form-item>
  37. <nz-form-item>
  38. <nz-form-label [nzSm]="8" [nzXs]="24" nzRequired>TimePicker</nz-form-label>
  39. <nz-form-control [nzSm]="16" [nzXs]="24">
  40. <nz-time-picker formControlName="timePicker"></nz-time-picker>
  41. </nz-form-control>
  42. </nz-form-item>
  43. <nz-form-item>
  44. <nz-form-control [nzXs]="{ span: 24, offset: 0 }" [nzSm]="{ span: 16, offset: 8 }">
  45. <button nz-button nzType="primary">Submit</button>
  46. </nz-form-control>
  47. </nz-form-item>
  48. </form>
  49. `,
  50. styles: [
  51. `
  52. form {
  53. max-width: 600px;
  54. }
  55. `
  56. ]
  57. })
  58. export class NzDemoFormTimeRelatedControlsComponent implements OnInit {
  59. validateForm: FormGroup;
  60. submitForm(): void {
  61. console.log(this.validateForm.value);
  62. }
  63. constructor(private fb: FormBuilder) {}
  64. ngOnInit(): void {
  65. this.validateForm = this.fb.group({
  66. datePicker: [null],
  67. datePickerTime: [null],
  68. monthPicker: [null],
  69. rangePicker: [[]],
  70. rangePickerTime: [[]],
  71. timePicker: [null]
  72. });
  73. }
  74. }

Form表单 - 图7

响应式表单验证

我们在 nz-form-control 上 提供了 nzValidateStatusnzHasFeedback 等属性,当使用响应式表单时,可以自己定义校验的时机和内容。

  • nzValidateStatus: 校验状态,默认自动从 nz-form-control 中的 NgControl 获得校验状态,也可以手动指定为特定的 NgControl
  • nzHasFeedback:用于给输入框添加反馈图标。
  • nzSuccessTipnzWarningTipnzErrorTipnzValidatingTip:设置不同状态校验文案。

当同一种状态下存在多种提示情况时,nzSuccessTipnzWarningTipnzErrorTipnzValidatingTip 均支持传入 TemplateRef<{ $implicit: FormControl } 类型,可以通过模板变量导出 FormControl 后用于切换不同的提示信息。

  1. import { Component } from '@angular/core';
  2. import { FormBuilder, FormControl, FormGroup, ValidationErrors, Validators } from '@angular/forms';
  3. import { Observable, Observer } from 'rxjs';
  4. @Component({
  5. selector: 'nz-demo-form-validate-reactive',
  6. template: `
  7. <form nz-form [formGroup]="validateForm" (ngSubmit)="submitForm(validateForm.value)">
  8. <nz-form-item>
  9. <nz-form-label [nzSpan]="7" nzRequired>Username</nz-form-label>
  10. <nz-form-control [nzSpan]="12" nzHasFeedback nzValidatingTip="Validating..." [nzErrorTip]="userErrorTpl">
  11. <input nz-input formControlName="userName" placeholder="async validate try to write JasonWood" />
  12. <ng-template #userErrorTpl let-control>
  13. <ng-container *ngIf="control.hasError('required')">
  14. Please input your username!
  15. </ng-container>
  16. <ng-container *ngIf="control.hasError('duplicated')">
  17. The username is redundant!
  18. </ng-container>
  19. </ng-template>
  20. </nz-form-control>
  21. </nz-form-item>
  22. <nz-form-item>
  23. <nz-form-label [nzSpan]="7" nzRequired>E-mail</nz-form-label>
  24. <nz-form-control [nzSpan]="12" nzHasFeedback [nzErrorTip]="emailErrorTpl">
  25. <input nz-input formControlName="email" placeholder="email" type="email" />
  26. <ng-template #emailErrorTpl let-control>
  27. <ng-container *ngIf="control.hasError('email')">
  28. The input is not valid E-mail!
  29. </ng-container>
  30. <ng-container *ngIf="control.hasError('required')">
  31. Please input your E-mail!
  32. </ng-container>
  33. </ng-template>
  34. </nz-form-control>
  35. </nz-form-item>
  36. <nz-form-item>
  37. <nz-form-label [nzSpan]="7" nzRequired>Password</nz-form-label>
  38. <div>
  39. <nz-form-control [nzSpan]="12" nzHasFeedback nzErrorTip="Please input your password!">
  40. <input nz-input type="password" formControlName="password" (ngModelChange)="validateConfirmPassword()" />
  41. </nz-form-control>
  42. </div>
  43. </nz-form-item>
  44. <nz-form-item>
  45. <nz-form-label [nzSpan]="7" nzRequired>Confirm Password</nz-form-label>
  46. <nz-form-control [nzSpan]="12" nzHasFeedback [nzErrorTip]="passwordErrorTpl">
  47. <input nz-input type="password" formControlName="confirm" placeholder="confirm your password" />
  48. <ng-template #passwordErrorTpl let-control>
  49. <ng-container *ngIf="control.hasError('required')">
  50. Please confirm your password!
  51. </ng-container>
  52. <ng-container *ngIf="control.hasError('confirm')">
  53. Password is inconsistent!
  54. </ng-container>
  55. </ng-template>
  56. </nz-form-control>
  57. </nz-form-item>
  58. <nz-form-item>
  59. <nz-form-label [nzSpan]="7" nzRequired>Comment</nz-form-label>
  60. <nz-form-control [nzSpan]="12" nzErrorTip="Please write something here!">
  61. <textarea formControlName="comment" nz-input rows="2" placeholder="write any thing"></textarea>
  62. </nz-form-control>
  63. </nz-form-item>
  64. <nz-form-item>
  65. <nz-form-control [nzOffset]="7" [nzSpan]="12">
  66. <button nz-button nzType="primary" [disabled]="!validateForm.valid">Submit</button>
  67. <button nz-button (click)="resetForm($event)">Reset</button>
  68. </nz-form-control>
  69. </nz-form-item>
  70. </form>
  71. `,
  72. styles: [
  73. `
  74. [nz-form] {
  75. max-width: 600px;
  76. }
  77. button {
  78. margin-left: 8px;
  79. }
  80. `
  81. ]
  82. })
  83. export class NzDemoFormValidateReactiveComponent {
  84. validateForm: FormGroup;
  85. submitForm(value: any): void {
  86. for (const key in this.validateForm.controls) {
  87. this.validateForm.controls[key].markAsDirty();
  88. this.validateForm.controls[key].updateValueAndValidity();
  89. }
  90. console.log(value);
  91. }
  92. resetForm(e: MouseEvent): void {
  93. e.preventDefault();
  94. this.validateForm.reset();
  95. for (const key in this.validateForm.controls) {
  96. this.validateForm.controls[key].markAsPristine();
  97. this.validateForm.controls[key].updateValueAndValidity();
  98. }
  99. }
  100. validateConfirmPassword(): void {
  101. setTimeout(() => this.validateForm.controls.confirm.updateValueAndValidity());
  102. }
  103. userNameAsyncValidator = (control: FormControl) =>
  104. new Observable((observer: Observer<ValidationErrors | null>) => {
  105. setTimeout(() => {
  106. if (control.value === 'JasonWood') {
  107. // you have to return `{error: true}` to mark it as an error event
  108. observer.next({ error: true, duplicated: true });
  109. } else {
  110. observer.next(null);
  111. }
  112. observer.complete();
  113. }, 1000);
  114. });
  115. confirmValidator = (control: FormControl): { [s: string]: boolean } => {
  116. if (!control.value) {
  117. return { error: true, required: true };
  118. } else if (control.value !== this.validateForm.controls.password.value) {
  119. return { confirm: true, error: true };
  120. }
  121. return {};
  122. };
  123. constructor(private fb: FormBuilder) {
  124. this.validateForm = this.fb.group({
  125. userName: ['', [Validators.required], [this.userNameAsyncValidator]],
  126. email: ['', [Validators.email, Validators.required]],
  127. password: ['', [Validators.required]],
  128. confirm: ['', [this.confirmValidator]],
  129. comment: ['', [Validators.required]]
  130. });
  131. }
  132. }

Form表单 - 图8

模板驱动表单验证

当使用模板驱动表单时,模板可以根据模板设定自动进行校验。

  • nzHasFeedback:用于给输入框添加反馈图标。
  • nzSuccessTipnzWarningTipnzErrorTipnzValidatingTip:设置不同状态校验文案。

当同一种状态下存在多种提示情况时,nzSuccessTipnzWarningTipnzErrorTipnzValidatingTip 均支持传入 TemplateRef<{ $implicit: NgModel } 类型,可以通过模板变量导出 NgModel 后用于切换不同的提示信息。

import { Component } from '@angular/core';

@Component({
  selector: 'nz-demo-form-validate-template',
  template: `
    <form nz-form>
      <nz-form-item>
        <nz-form-label [nzSpan]="5">Required</nz-form-label>
        <nz-form-control nzHasFeedback [nzSpan]="12" nzErrorTip="Input is required">
          <input nz-input [ngModel]="'Required Input'" name="required" required />
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-label [nzSpan]="5">MaxLength</nz-form-label>
        <nz-form-control nzHasFeedback [nzSpan]="12" nzErrorTip="MaxLength is 6">
          <input nz-input [ngModel]="'MaxLength is 6'" name="maxlength" maxlength="6" />
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-label [nzSpan]="5">MinLength</nz-form-label>
        <nz-form-control nzHasFeedback [nzSpan]="12" nzErrorTip="MinLength is 6">
          <input nz-input [ngModel]="'MinLength is 6'" name="minlength" minlength="6" />
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-label [nzSpan]="5">Email</nz-form-label>
        <nz-form-control nzHasFeedback [nzSpan]="12" nzErrorTip="Email is not valid">
          <input nz-input [ngModel]="'Input Email'" name="email" email />
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-label [nzSpan]="5">Pattern</nz-form-label>
        <nz-form-control nzHasFeedback [nzSpan]="12" nzErrorTip="Pattern not match">
          <input nz-input [ngModel]="'Match pattern'" name="pattern" pattern=".{3,}" />
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-label [nzSpan]="5">Mix</nz-form-label>
        <nz-form-control nzHasFeedback [nzSpan]="12" [nzErrorTip]="combineTpl">
          <input
            nz-input
            [ngModel]="'MaxLength is 12 and MinLength is 6'"
            name="mix"
            minlength="6"
            maxlength="12"
            required
          />
          <ng-template #combineTpl let-control>
            <ng-container *ngIf="control.hasError('maxlength')">MaxLength is 12</ng-container>
            <ng-container *ngIf="control.hasError('minlength')">MinLength is 6</ng-container>
            <ng-container *ngIf="control.hasError('required')">Input is required</ng-container>
          </ng-template>
        </nz-form-control>
      </nz-form-item>
    </form>
  `,
  styles: [
    `
      [nz-form] {
        max-width: 600px;
      }
    `
  ]
})
export class NzDemoFormValidateTemplateComponent {}

Form表单 - 图9

手动指定表单状态

用户可以在通过 nz-form-controlnzValidateStatus 属性直接设定表单的状态。

  • nzValidateStatus: 校验状态,可选 'success', 'warning', 'error', 'validating'。
  • nzHasFeedback:用于给输入框添加反馈图标。
  • nzSuccessTipnzWarningTipnzErrorTipnzValidatingTip:设置不同状态校验文案。
import { Component } from '@angular/core';

@Component({
  selector: 'nz-demo-form-validate-static',
  template: `
    <form nz-form>
      <nz-form-item>
        <nz-form-label [nzSpan]="5">Fail</nz-form-label>
        <nz-form-control
          nzValidateStatus="error"
          [nzSpan]="12"
          nzErrorTip="Should be combination of numbers & alphabets"
        >
          <input nz-input [ngModel]="'unavailable choice'" name="errorValid" />
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-label [nzSpan]="5">Warning</nz-form-label>
        <nz-form-control nzValidateStatus="warning" [nzSpan]="12">
          <input nz-input [ngModel]="'Warning'" name="warningValid" />
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-label [nzSpan]="5">Validating</nz-form-label>
        <nz-form-control
          [nzSpan]="12"
          nzValidateStatus="validating"
          nzHasFeedback
          nzValidatingTip="I'm validating the content"
        >
          <input nz-input [ngModel]="'The content is being validated'" name="validating" />
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-label [nzSpan]="5">Success</nz-form-label>
        <nz-form-control [nzSpan]="12" nzValidateStatus="success" nzHasFeedback>
          <input nz-input [ngModel]="'The content'" name="successValid" />
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-label [nzSpan]="5">Warning</nz-form-label>
        <nz-form-control
          [nzSpan]="12"
          nzValidateStatus="warning"
          nzHasFeedback
          nzWarningTip="Should be combination of numbers & alphabets"
        >
          <input nz-input [ngModel]="'Warning'" name="warningHighValid" />
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-label [nzSpan]="5">Fail</nz-form-label>
        <nz-form-control
          [nzSpan]="12"
          nzValidateStatus="error"
          nzHasFeedback
          nzErrorTip="Should be combination of numbers & alphabets"
        >
          <input nz-input [ngModel]="'unavailable choice'" name="invalidValid" />
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-label [nzSpan]="5">Success</nz-form-label>
        <nz-form-control [nzSpan]="12" nzValidateStatus="success" nzHasFeedback>
          <nz-date-picker name="date-picker-success"></nz-date-picker>
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-label [nzSpan]="5">Warning</nz-form-label>
        <nz-form-control [nzSpan]="12" nzValidateStatus="warning" nzHasFeedback>
          <nz-time-picker name="time-picker-warning"></nz-time-picker>
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-label [nzSpan]="5">Error</nz-form-label>
        <nz-form-control [nzSpan]="12" nzValidateStatus="error" nzHasFeedback>
          <nz-select name="select-error" [ngModel]="'Option 1'">
            <nz-option nzValue="Option 1" nzLabel="Option 1"></nz-option>
            <nz-option nzValue="Option 2" nzLabel="Option 2"></nz-option>
          </nz-select>
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-label [nzSpan]="5">Validating</nz-form-label>
        <nz-form-control [nzSpan]="12" nzValidateStatus="validating" nzHasFeedback>
          <nz-select name="select-validate" [ngModel]="'Option 2'">
            <nz-option nzValue="Option 1" nzLabel="Option 1"></nz-option>
            <nz-option nzValue="Option 2" nzLabel="Option 2"></nz-option>
          </nz-select>
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-label [nzSpan]="5">Success</nz-form-label>
        <nz-form-control [nzSpan]="12" nzValidateStatus="success" nzHasFeedback>
          <nz-input-number name="inputnumber-success" style="width:100%"></nz-input-number>
        </nz-form-control>
      </nz-form-item>
    </form>
  `,
  styles: [
    `
      [nz-form] {
        max-width: 600px;
      }

      nz-date-picker ::ng-deep .ant-calendar-picker {
        width: 100%;
      }

      nz-date-picker,
      nz-time-picker {
        width: 100%;
      }
    `
  ]
})
export class NzDemoFormValidateStaticComponent {}

Form表单 - 图10

表单联动

使用 setValue 来动态设置其他控件的值。

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

@Component({
  selector: 'nz-demo-form-coordinated',
  template: `
    <form nz-form [formGroup]="validateForm" (ngSubmit)="submitForm()">
      <nz-form-item>
        <nz-form-label [nzSpan]="5" nzRequired nzFor="note">Note</nz-form-label>
        <nz-form-control [nzSpan]="12" nzErrorTip="Please input your username!">
          <input id="note" type="text" nz-input formControlName="note" />
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-label [nzSpan]="5" nzFor="gender" nzRequired>Gender</nz-form-label>
        <nz-form-control [nzSpan]="12" nzErrorTip="Please select your gender!">
          <nz-select
            id="gender"
            formControlName="gender"
            nzPlaceHolder="Select a option and change input text above"
            (ngModelChange)="genderChange($event)"
          >
            <nz-option nzValue="male" nzLabel="male"></nz-option>
            <nz-option nzValue="female" nzLabel="female"></nz-option>
          </nz-select>
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-control [nzSpan]="12" [nzOffset]="5">
          <button nz-button nzType="primary">Submit</button>
        </nz-form-control>
      </nz-form-item>
    </form>
  `,
  styles: [
    `
      [nz-form] {
        max-width: 600px;
      }
    `
  ]
})
export class NzDemoFormCoordinatedComponent implements OnInit {
  validateForm: FormGroup;

  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
  }

  genderChange(value: string): void {
    this.validateForm.get('note')!.setValue(value === 'male' ? 'Hi, man!' : 'Hi, lady!');
  }

  constructor(private fb: FormBuilder) {}

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      note: [null, [Validators.required]],
      gender: [null, [Validators.required]]
    });
  }
}

Form表单 - 图11

表单布局

表单有三种布局。

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

@Component({
  selector: 'nz-demo-form-layout',
  template: `
    <form
      nz-form
      [nzLayout]="validateForm.get('formLayout')?.value"
      [formGroup]="validateForm"
      (ngSubmit)="submitForm()"
    >
      <nz-form-item>
        <nz-form-label [nzSpan]="isHorizontal ? 4 : null">Form Layout</nz-form-label>
        <nz-form-control [nzSpan]="isHorizontal ? 14 : null">
          <nz-radio-group formControlName="formLayout">
            <label nz-radio-button [nzValue]="'horizontal'">Horizontal</label>
            <label nz-radio-button [nzValue]="'vertical'">Vertical</label>
            <label nz-radio-button [nzValue]="'inline'">Inline</label>
          </nz-radio-group>
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-label [nzSpan]="isHorizontal ? 4 : null">Field A</nz-form-label>
        <nz-form-control [nzSpan]="isHorizontal ? 14 : null" nzErrorTip="Please input your username!">
          <input nz-input formControlName="fieldA" placeholder="input placeholder" />
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-label [nzSpan]="isHorizontal ? 4 : null">Field B</nz-form-label>
        <nz-form-control [nzSpan]="isHorizontal ? 14 : null" nzErrorTip="Please input your Password!">
          <input nz-input formControlName="filedB" placeholder="input placeholder" />
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-control [nzSpan]="isHorizontal ? 14 : null" [nzOffset]="isHorizontal ? 4 : null">
          <button nz-button nzType="primary">Submit</button>
        </nz-form-control>
      </nz-form-item>
    </form>
  `,
  styles: [
    `
      [nz-form]:not(.ant-form-inline):not(.ant-form-vertical) {
        max-width: 600px;
      }
    `
  ]
})
export class NzDemoFormLayoutComponent implements OnInit {
  validateForm: FormGroup;

  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
  }

  get isHorizontal(): boolean {
    return this.validateForm.controls.formLayout && this.validateForm.controls.formLayout.value === 'horizontal';
  }

  constructor(private fb: FormBuilder) {}

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      formLayout: ['horizontal'],
      fieldA: [null, [Validators.required]],
      filedB: [null, [Validators.required]]
    });
  }
}

Form表单 - 图12

动态校验规则

根据不同情况执行不同的校验规则。

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

@Component({
  selector: 'nz-demo-form-dynamic-rule',
  template: `
    <form nz-form [formGroup]="validateForm" (ngSubmit)="submitForm()">
      <nz-form-item>
        <nz-form-label [nzSpan]="4" nzRequired nzFor="name">Name</nz-form-label>
        <nz-form-control [nzSpan]="8" nzErrorTip="Please input your name">
          <input type="text" nz-input formControlName="name" placeholder="Please input your name" />
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-label [nzSpan]="4" nzFor="nickname" [nzRequired]="validateForm.get('required')?.value"
          >Nickname</nz-form-label
        >
        <nz-form-control [nzSpan]="8" nzErrorTip="Please input your nickname">
          <input type="text" nz-input formControlName="nickname" placeholder="Please input your nickname" />
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-control [nzSpan]="8" [nzOffset]="4">
          <label nz-checkbox formControlName="required" (ngModelChange)="requiredChange($event)"
            >Nickname is required</label
          >
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-control [nzSpan]="8" [nzOffset]="4">
          <button nz-button nzType="primary">Check</button>
        </nz-form-control>
      </nz-form-item>
    </form>
  `
})
export class NzDemoFormDynamicRuleComponent implements OnInit {
  validateForm: FormGroup;

  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
  }

  requiredChange(required: boolean): void {
    if (!required) {
      this.validateForm.get('nickname')!.clearValidators();
      this.validateForm.get('nickname')!.markAsPristine();
    } else {
      this.validateForm.get('nickname')!.setValidators(Validators.required);
      this.validateForm.get('nickname')!.markAsDirty();
    }
    this.validateForm.get('nickname')!.updateValueAndValidity();
  }

  constructor(private fb: FormBuilder) {}

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      name: [null, [Validators.required]],
      nickname: [null],
      required: [false]
    });
  }
}

API

[nz-form]directive

参数说明类型默认值
[nzLayout]表单布局'horizontal' | 'vertical' | 'inline''horizontal'
[nzNoColon]配置 nz-form-label[nzNoColon] 的默认值booleanfalse

nz-form-itemcomponent

表单项用于区分表单中不同的区域,包含表单域和表单标签(可选)。

所有 nz-row 的参数在 nz-form-item 上均可直接使用。

参数说明类型默认值
[nzFlex]是否Flex布局booleanfalse

nz-form-labelcomponent

用于标示当前表单项的内容,可选。

所有 nz-col 的参数在 nz-form-label 上均可直接使用。

参数说明类型默认值
[nzRequired]当前项是否为必填,仅影响样式booleanfalse
[nzNoColon]是否不显示 label 后面的冒号booleanfalse
[nzFor]label 标签的 for 属性string-

nz-form-controlcomponent

注意:由于 Angular Form 目前提供的状态变更订阅不完整。手动更改表单状态时,例如 markAsDirty 后,需要执行 updateValueAndValidity 通知 nz-form-control 进行状态变更。

表单一定会包含表单域,表单域可以是输入控件,标准表单域,标签,下拉菜单,文本域等。

所有 nz-col 的参数在 nz-form-control 上均可直接使用。

参数说明类型默认值
[nzValidateStatus]会根据传入的 FormControlNgModel 自动生成校验状态,也可以直接指定状态,不传入时默认值为 nz-form-control 中包裹的第一个 FormControlNgModel'success' | 'warning' | 'error' | 'validating' | FormControl | NgModelnz-form-control 中包裹的第一个 FormControlNgModel
[nzHasFeedback]配合 nzValidateStatus 属性使用,展示校验状态图标booleanfalse
[nzExtra]用于显示表单额外提示信息string | TemplateRef<void>-
[nzSuccessTip]校验状态 success 时提示信息string | TemplateRef<{ $implicit: FormControl | NgModel }>-
[nzWarningTip]校验状态 warning 时提示信息string | TemplateRef<{ $implicit: FormControl | NgModel }>-
[nzErrorTip]校验状态 error 时提示信息string | TemplateRef<{ $implicit: FormControl | NgModel }>-
[nzValidatingTip]正在校验时提示信息string | TemplateRef<{ $implicit: FormControl | NgModel }>-

nz-form-splitcomponent

用于显示分隔符 -

nz-form-textcomponent

nz-form-control 中直接显示文本