如何在 Angular 的反应表单中设置表单控件的值

2023-12-11

我是角度新手。实际上,我正在尝试从服务订阅数据,并将该数据传递给我的表单控件(例如,它就像编辑表单)。

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不需要在参数中指定所有控件即可更新/设置表单控件的值。另一方面,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 的事情对象解构,您可能有兴趣这样做 ????

const { user, questioning } = this.question;

this.editqueForm.patchValue({
  user,
  questioning
});

Ta-dah!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Angular 的反应表单中设置表单控件的值 的相关文章

随机推荐