首页 > 解决方案 > 如何在 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})
}

谁能告诉我如何设置值来挖掘反应形式。请给我建议。

标签: angularangular7angular-reactive-forms

解决方案


可以使用 patchValue 和 setValue 来设置或更新响应式表单表单控件的值。但是,在某些情况下使用patchValue可能会更好。

patchValue不需要在参数中指定所有控件以更新/设置表单控件的值。另一方面,setValue要求填写所有表单控件值,如果您的任何控件未在参数中指定,它将返回错误。

在这种情况下,我们将要使用 patchValue,因为我们只更新userand 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
});

达达!


推荐阅读