angular - 如何在 Angular 的反应式表单中设置表单控件的值
问题描述
大家好,我是 Angular 的新手。实际上,我正在尝试从服务订阅数据,并且该数据正在传递给我的表单控件(例如,它就像一个编辑表单)。
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormArray, FormControl } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { QuestionService } from '../shared/question.service';
@Component({
selector: 'app-update-que',
templateUrl: './update-que.component.html',
styleUrls: ['./update-que.component.scss']
})
export class UpdateQueComponent implements OnInit {
questionsTypes = ['Text Type', 'Multiple choice', 'Single Select'];
selectedQuestionType: string = "";
question: any = {};
constructor(private route: ActivatedRoute, private router: Router,
private qService: QuestionService, private fb: FormBuilder) {
}
ngOnInit() {
this.getQuebyid();
}
getQuebyid(){
this.route.params.subscribe(params => {
this.qService.editQue([params['id']]).subscribe(res =>{
this.question = res;
});
});
}
editqueForm = this.fb.group({
user: [''],
questioning: ['', Validators.required],
questionType: ['', Validators.required],
options: new FormArray([])
})
setValue(){
this.editqueForm.setValue({user: this.question.user, questioning: this.question.questioning})
}
}
如果我[(ngModule)]
在表单字段上使用将值设置为我的元素,它工作正常并显示警告,它将在 Angular 7 版本中被弃用。
<textarea formControlName="questioning" [(ngModule)]="question.questioning" cols="70" rows="4"></textarea>
因此,我通过以下操作将值设置为我的表单控件,但该元素未显示这些值。
setValue(){
this.editqueForm.setValue({user: this.question.user, questioning: this.question.questioning})
}
谁能告诉我如何设置值来挖掘反应形式。请给我建议。
解决方案
可以使用 patchValue 和 setValue 来设置或更新响应式表单表单控件的值。但是,在某些情况下使用patchValue可能会更好。
patchValue
不需要在参数中指定所有控件以更新/设置表单控件的值。另一方面,setValue
要求填写所有表单控件值,如果您的任何控件未在参数中指定,它将返回错误。
在这种情况下,我们将要使用 patchValue,因为我们只更新user
and questioning
:
this.qService.editQue([params["id"]]).subscribe(res => {
this.question = res;
this.editqueForm.patchValue({
user: this.question.user,
questioning: this.question.questioning
});
});
编辑:如果你想做一些 ES6 的Object Destructuring,你可能有兴趣这样做
const { user, questioning } = this.question;
this.editqueForm.patchValue({
user,
questioning
});
达达!
推荐阅读
- javascript - Firebase Javascript Ajax 和会话问题
- web-scraping - 抓取衣物的性别
- node.js - 如何使用 node.js 比较 mongoDB ObjectIds 并删除文档数组中的重复项?
- webrtc - 将 SIP 与 webRTC 连接
- docker - 如何更改 WordPress 容器中 www-data 的 UID 和 GID 以匹配 linux 中的主机
- recursion - 消除上下文无关语法中的左递归
- reactjs - 出现错误:模块解析失败:反应 js 中的意外令牌(1:0)
- angular - 这段代码有什么作用?Angular Firebase 身份验证
- c# - 用于 XML 序列化的 C# 类
- android - 使用“removeBond”方法取消配对的蓝牙设备在 redmi android 设备中不起作用