- patchValue:设置表单控件的值(可以设置全部,也可以设置其中某一个,其他不受影响)
- setValue:设置表单控件的值 (设置全部,不能排除任何一个)
- valueChanges:当表单控件的值发生变化时被触发的事件
- reset:表单内容置空 ```typescript import { FormGroup, FormControl } from ‘@angular/forms’; import { Component, OnInit } from ‘@angular/core’;
@Component({ selector: ‘app-method’, templateUrl: ‘./method.component.html’, styleUrls: [‘./method.component.scss’] })
export class MethodComponent implements OnInit { form: FormGroup = new FormGroup({ firstName: new FormControl(), lastName: new FormControl(), })
// 设置表单控件的值(可以设置全部,也可以设置其中某一个,其他不受影响)onPatchValue() {this.form.patchValue({firstName: 'test',})}// 设置表单控件的值 (设置全部,不能排除任何一个)onSetValue() {// 只修改一个 firstName 不行this.form.patchValue({firstName: 'test',lastName: 'test'})}onReset() {this.form.reset()}onSubmit() {}constructor() { }ngOnInit(): void {// 当表单控件的值发生变化时被触发的事件this.form.get('lastName')?.valueChanges.subscribe((value) => {console.log(value)})}
}
```typescript<form [formGroup]="form" (submit)="onSubmit()"><input type="text" formControlName="firstName"><input type="text" formControlName="lastName"><button (click)="onPatchValue()">patchValue</button><button (click)="onSetValue()">setValue</button><button (click)="onReset()">reset</button><button>提交</button></form>
