angular - 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>
我应该如何尝试在组件生命周期中以我的反应形式设置默认值?
解决方案
只是在你的component.ts
myForm: FormGroup;
create_form() {
this.myForm= new FormGroup({
stages: new FormControl(['one','two', 'three'], [Validators.required]),
...
});
}
并在您的constructor
constructor() {
this.create_form();
}
推荐阅读
- javascript - jQuery 加载。等待 500 毫秒
- mongodb - 如果未在架构中列出,如何使 Mongoose 不保存字段
- c# - 如何使用 ASP.NET MVC 忽略路由中的动作名称?
- apache - 带 SSO 的 Delphi Apache 模块
- node.js - 如何在 NodeJS 中接收 pdf 文件
- java - 自定义过滤器突然打破@WebMvcTest
- ruby-on-rails - 不允许的参数:Rails 5.2
- python - 如何从数据框中丢弃具有单个字符的名称?
- java - Java XML Transformer Node to String remove namespace
- java - 如何将凭证传递给 Translation API v3?