我有一个接受各种输入的组件,这些输入又在该组件内的反应形式内的选择中使用。表单应该将这些值用作表单中的默认值,但是当我尝试创建表单时,似乎总是没有将它们初始化。
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输入的键值数组填充表单上的stage属性。但是,控制台日志显示该数组为空
[]
当我通读角度生命周期挂钩文档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>
我该如何尝试在组件生命周期中以反应形式设置默认值?
答案 0 :(得分:0)
只需在您的deno run -A --unstable https://deno.land/x/deno_check_updates/main.ts -f import_map.json
component.ts
并在您的myForm: FormGroup;
create_form() {
this.myForm= new FormGroup({
stages: new FormControl(['one','two', 'three'], [Validators.required]),
...
});
}
constructor