Angular 角度10分量输入为反应形式默认值

Angular 角度10分量输入为反应形式默认值,angular,angular-reactive-forms,Angular,Angular Reactive Forms,我有一个组件,它接受各种输入,这些输入依次在该组件中的一个反应形式中的选择中使用。表单应该使用这些值作为表单中的默认值,但在我尝试创建表单时,它们似乎始终没有初始化 export class GenericFilterComponent implements OnInit { @Input() stageOptions: IKeyValuePair[]; ... myForm: FormGroup; constructor(private fb: FormBuilder)

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

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输入中的键值数组填充表单上的stages属性。但是,控制台日志显示阵列为空

[]
当我阅读angular lifecycle hooks文档时,它说ngOnInit在ngOnChanges之后调用,ngOnChanges是:

Called before ngOnInit() and whenever one or more data-bound input properties change.
所以我认为输入值应该已经设置好了。我尝试了其他的生命周期挂钩,将它们放到控制台上,最终只有:ngochanges()、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>

阶段
全选
{{stage.value}}

在组件生命周期中,我应该如何在被动形式中设置默认值?

只需在您的
组件中这样做即可

myForm: FormGroup;

create_form() {
  this.myForm= new FormGroup({
    stages: new FormControl(['one','two', 'three'], [Validators.required]),
    ...
  });
}
并在
构造函数中调用此函数

  constructor() {
    this.create_form();
  }

只需在
组件中执行此操作即可。ts

myForm: FormGroup;

create_form() {
  this.myForm= new FormGroup({
    stages: new FormControl(['one','two', 'three'], [Validators.required]),
    ...
  });
}
并在
构造函数中调用此函数

  constructor() {
    this.create_form();
  }

你能展示你的html吗?完成了。它实际上只是使用angular material design Component填充了一个多选下拉菜单。您可以显示您的html页面吗。它实际上只是使用angular material design Component填充了一个多选的水滴,具有静态值就可以了,但我想从@Input()获取它们具有静态值就可以了,但我想从@Input()获取它们