angular响应式表单 setValue和pathValue的区别

<p>把表单控件分组</p>


<form [formGroup]="profileForm"  (ngSubmit)="onSubmit()">

    <label for="first-name">First Name: </label>
    <!-- 配合表单使用要用"formControlName",单个控件使用"formControl" -->
    <input id="first-name" type="text" formControlName="firstName">
  
    <label for="last-name">Last Name: </label>
    <input id="last-name" type="text" formControlName="lastName">
    
    <div formGroupName="address">
        <!-- 在模板中对这个嵌套表单分组。 -->
        <h2>Address</h2>
      
        <label for="street">Street: </label>
        <input id="street" type="text" formControlName="street">
      
        <label for="city">City: </label>
        <input id="city" type="text" formControlName="city">
      
        <label for="state">State: </label>
        <input id="state" type="text" formControlName="state">
      
        <label for="zip">Zip Code: </label>
        <input id="zip" type="text" formControlName="zip">
      </div>

    <!-- buttton要设置为 type="submit" -->
    <button type="submit" class="btn btn-info" (click)="updateProfile()">使用patchValue更新部分数据</button>
    <button type="submit" class="btn btn-info" (click)="setValue()">使用setValue更新部分数据</button>

    <button type="submit" class="btn btn-primary" [disabled]="!profileForm.valid">Submit</button>
 </form>
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
  selector: 'app-profile-editor',
  templateUrl: './profile-editor.component.html',
  styleUrls: ['./profile-editor.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ProfileEditorComponent {
  profileForm = new FormGroup({
    firstName: new FormControl(''),
    lastName: new FormControl(''),
    address: new FormGroup({
      street: new FormControl(''),
      city: new FormControl(''),
      state: new FormControl(''),
      zip: new FormControl('')
    })
  })
  onSubmit() {
    console.warn(this.profileForm.value);
    console.warn(this.profileForm.get('firstName')!.value);
  }
  
  updateProfile() {
    // patchValue可以更新表单的部分数据
    this.profileForm.patchValue({
      firstName: 'Nancy',
      address: {
        street: '123 Drew Street'
      }
    });
  }
  setValue() {
    // setValue可以更新的数据,但必须要把所有的FormGroup中表单字段加上
    this.profileForm.setValue({
      firstName: 'firstName',
      lastName: 'lastName',
      address: {
        street: 'street',
        city: 'city',
        state: 'state',
        zip: 'zip',
      }
    })
  }
}

 

posted @ 2023-03-12 10:21  赵辉Coder  阅读(43)  评论(0编辑  收藏  举报