添加基础表单控件

首先导入在module中导入ReactiveFormsModule模块

  1. import { ReactiveFormsModule } from '@angular/forms';
  2. @NgModule({
  3. imports: [
  4. //......
  5. ReactiveFormsModule
  6. ],
  7. })

生成一个新组件:ng generate component NameEditor
导入 FormControl 类并创建一个 FormControl 的新实例,将其保存为类的属性

  1. //name-editor.component.ts
  2. import { FormControl } from '@angular/forms';
  3. export class NameEditorComponent {
  4. name = new FormControl('');
  5. }

将控件在模板和组件类中关联起来,通过name.value可以访问控件的值

  1. {{name.value}}
  2. <input type="text" [formControl]="name">

使用setValue可以设置控件的value

  1. this.name.setValue('string');

控件分组

  1. // 导入所需类
  2. import { FormGroup, FormControl } from '@angular/forms';
  3. export class ProfileEditorComponent {
  4. // 将独立的控件收集到一个控件组中
  5. profileForm = new FormGroup({
  6. firstName: new FormControl(''),
  7. lastName: new FormControl(''),
  8. });
  9. onClick(): void{
  10. // 获取组中某个控件的值
  11. console.log(this.profileForm.value.firstName);
  12. // 设置组中控件的value
  13. this.profileForm.setValue({ firstName: 'sheng' , lastName: 'chang'});
  14. }
  15. }
  1. <form [formGroup]="profileForm"><!--把FormGroup模型关联到视图-->
  2. <label>First Name:
  3. <input type="text" formControlName="firstName">
  4. </label>
  5. <label>Last Name:
  6. <input type="text" formControlName="lastName">
  7. </label>
  8. <button (click)="onClick()"></button>
  9. </form>

更新部分数据模型

setValue()

  • 使用 setValue() 方法来为单个控件设置新值。 setValue() 方法会严格遵循表单组的结构,并整体性替换控件的值。
  • FormGroup.setValue({ firstName: 'sheng' , lastName: 'chang'});

    patchValue()

  • 使用 patchValue() 方法可以用对象中所定义的任何属性为表单模型进行替换。

    1. updateProfile() {
    2. this.profileForm.patchValue({
    3. firstName: 'Nancy',
    4. address: {
    5. street: '123 Drew Street'
    6. }
    7. });
    8. }

    区别

  • setValue() 方法的严格检查可以帮助你捕获复杂表单嵌套中的错误

  • patchValue() 在遇到那些错误时可能会默默的失败。

    使用 FormBuilder 服务生成控件

    1. import { FormBuilder } from '@angular/forms';
    2. export class ProfileEditorComponent {
    3. profileForm = this.fb.group({
    4. firstName: [''],
    5. lastName: [''],
    6. address: this.fb.group({
    7. street: [''],
    8. city: [''],
    9. state: [''],
    10. zip: ['']
    11. }),
    12. });
    13. constructor(private fb: FormBuilder) { }
    14. }

    创建动态表单

    定义FormArray控件

    ```typescript import { FormArray } from ‘@angular/forms’; export class ProfileEditorComponent { profileForm = this.fb.group({ firstName: [‘’, Validators.required], lastName: [‘’], address: this.fb.group({ street: [‘’], city: [‘’], state: [‘’], zip: [‘’], }), aliases: this.fb.array([this.fb.control(‘’)]), }); }

  1. <a name="jnw49"></a>
  2. ## 访问FormArray控件,向其中动态增加控件
  3. ```typescript
  4. get aliases() {
  5. return this.profileForm.get('aliases') as FormArray;
  6. }
  7. addAlias() {
  8. this.aliases.push(this.fb.control(''));
  9. }

在模板中显示表达数组

  1. <div formArrayName="aliases">
  2. <h3>Aliases</h3>
  3. <button (click)="addAlias()">Add Alias</button>
  4. <div *ngFor="let alias of aliases.controls; let i = index">
  5. <!-- The repeated alias template -->
  6. <label>
  7. Alias:
  8. <input type="text" [formControlName]="i" />
  9. </label>
  10. </div>
  11. </div>

demo

image.png

  1. <p>姓名 : {{ profileForm.get("name").value }}</p>
  2. <p>电话 : {{ profileForm.get("tel").value }}</p>
  3. <p>省份 : {{ profileForm.get("address").get("province").value }}</p>
  4. <p>城市 : {{ profileForm.get("address").get("citys").value }}</p>
  5. <p>爱好 : {{ profileForm.get("hobbys").value | json }}</p>
  6. <h1>个人资料</h1>
  7. <form [formGroup]="profileForm">
  8. <h2>基本信息</h2>
  9. <label
  10. >姓名:
  11. <input type="text" formControlName="name" />
  12. </label>
  13. <label
  14. >电话:
  15. <input type="text" formControlName="tel" />
  16. </label>
  17. <div formGroupName="address">
  18. <h2>住址</h2>
  19. <label
  20. >省份:
  21. <input type="text" formControlName="province" />
  22. </label>
  23. <label
  24. >地市:
  25. <input type="text" formControlName="citys" />
  26. </label>
  27. </div>
  28. <div formArrayName="hobbys">
  29. <h2>爱好</h2>
  30. <button (click)="addHobbys()">增加</button>
  31. <br />
  32. <label *ngFor="let hobby of hobbys.controls; let i = index">
  33. <!-- <span>爱好 {{i+1}} : </span> -->
  34. <input type="text" [formControlName]="i" />
  35. <button (click)="delHobby(i)">x</button>
  36. <br />
  37. </label>
  38. </div>
  39. </form>
  1. import { Component, OnInit } from '@angular/core';
  2. import { FormArray, FormBuilder, FormControl, FormGroup } from '@angular/forms';
  3. @Component({
  4. selector: 'app-demo2',
  5. templateUrl: './demo2.component.html',
  6. styleUrls: ['./demo2.component.css'],
  7. })
  8. export class Demo2Component implements OnInit {
  9. profileForm = this.fb.group({
  10. name: [''],
  11. tel: [''],
  12. address: this.fb.group({
  13. province: [''],
  14. citys: [''],
  15. }),
  16. hobbys: this.fb.array([
  17. this.fb.control(''),
  18. this.fb.control('')
  19. ]),
  20. });
  21. get hobbys(): FormArray {
  22. return this.profileForm.get('hobbys') as FormArray;
  23. }
  24. addHobbys(): void {
  25. this.hobbys.push(this.fb.control(''));
  26. }
  27. delHobby(i: number): void {
  28. this.hobbys.removeAt(i);
  29. }
  30. constructor(private fb: FormBuilder) {}
  31. ngOnInit(): void {}
  32. }