如何以角度设置反应式中的形控值 [英] How to set value to form control in Reactive Forms in 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)]
将值设置为我的元素,则它工作正常,并显示警告,它在角度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
和questioning
:
this.qService.editQue([params["id"]]).subscribe(res => {
this.question = res;
this.editqueForm.patchValue({
user: this.question.user,
questioning: this.question.questioning
});
});
编辑:如果您想做一些ES6Object Destructuring,您可能有兴趣这样做,而不是🙃
const { user, questioning } = this.question;
this.editqueForm.patchValue({
user,
questioning
});
答对!
这篇关于如何以角度设置反应式中的形控值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文