首页 > 解决方案 > Angular 10 组件输入到反应形式默认值

问题描述

我有一个组件,它接受各种输入,而这些输入又在该组件内的反应形式中的选择中使用。表单应该使用这些值作为表单中的默认值,但是当我尝试创建表单时,它们似乎总是没有被初始化。

export class GenericFilterComponent implements OnInit {

  @Input() stageOptions: IKeyValuePair[];
  ...

  myForm: FormGroup;

  constructor(private fb: FormBuilder) { }

  ngOnInit(): void {
    console.log(this.stageOptions);
    this.myForm = this.fb.group({
      stages: [this.stageOptions.map(item => item.key), Validators.required],
      ...

这应该使用来自 statusOptions 输入的键值数组填充表单上的阶段属性。然而,控制台日志显示数组为空

[]

当我阅读角度生命周期钩子文档https://angular.io/guide/lifecycle-hooks时,它说 ngOnInit 在 ngOnChanges 之后调用:

Called before ngOnInit() and whenever one or more data-bound input properties change.

所以我会认为输入值会被设置。我已经尝试过使用其他生命周期挂钩,将它们放到控制台中,最终只有 ngOnchanges()、ngDoCheck()、ngAfterContentChecked() 和 ngAfterViewChecked() 才能记录数组。但是这些被调用了很多次。

html

<mat-form-field appearance="fill">
  <mat-label>Stage</mat-label>
  <mat-select formControlName="stages" multiple required>
    <mat-option [value]="-1" (click)="selectAllStages(stage)" #stage>Select All</mat-option>
    <mat-option *ngFor="let stage of stageOptions" [value]="stage.key">{{stage.value}}
    </mat-option>
  </mat-select>
</mat-form-field>

我应该如何尝试在组件生命周期中以我的反应形式设置默认值?

标签: angularangular-reactive-forms

解决方案


只是在你的component.ts

myForm: FormGroup;

create_form() {
  this.myForm= new FormGroup({
    stages: new FormControl(['one','two', 'three'], [Validators.required]),
    ...
  });
}

并在您的constructor

  constructor() {
    this.create_form();
  }

推荐阅读