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', } }) } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具