我在 Angular 中使用我们拥有的各种形式的动态表单模式。这对我们来说是一种方便的方式,因为我们只需要在其中定义我们的控件ngOnInit
,它就会动态地构建我们需要的表单。但是,有些形式的值必须初始化,并且可以使用 async/await 检索一些值。
这是动态表单的问题,因为当我初始化异步数据时,它会在控制台上引发错误,并且表单没有显示在视图上。
我试图在 ngOnInit 上添加异步并等待异步数据。如示例代码所示:
async ngOnInit() {
const pageUrl = await this.fooService.getTabUrl();
const security = this.barService.getSecurity();
const controls: Array<ControlBase<any>> = [
new ControlTextbox({
key: "url",
order: 0,
readonly: true,
type: "text",
value: pageUrl
}),
new ControlDropdown({
key: "security",
label: "Security",
order: 2,
options: security,
type: "dropdown",
value: security[0].id
})
];
this.controls = controls;
}
我还在视图上添加了一个异步管道:
<form class="{{formClass}}" (ngSubmit)="onSubmit()" [formGroup]="form" role="form">
<app-form-control *ngFor="let ctrl of controls | async" [control]="ctrl | async" [form]="form | async"></app-form-control>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block" [disabled]="!form.valid">{{btnText}}</button>
</div>
</form>
但是,这是行不通的。
附加代码:
export class FormControlComponent implements OnInit {
@Input() public control: ControlBase<string | boolean | undefined>;
@Input() public form: FormGroup;
constructor() { }
get valid() {
return this.form.controls[this.control.key].valid;
}
get invalid() {
return !this.form.controls[this.control.key].valid && this.form.controls[this.control.key].touched;
}
ngOnInit() { }
}
export class DynamicFormComponent implements OnInit {
@Input() public controls: Array<ControlBase<any>> = [];
@Input() public btnText = "Submit";
@Output() public formSubmit: EventEmitter<any> = new EventEmitter<any>();
public form: FormGroup;
constructor(public _controlService: FormControlService) { }
ngOnInit() {
const sortedControls = this.controls.sort((a, b) => a.order - b.order);
this.form = this._controlService.toControlGroup(sortedControls);
}
onSubmit(): void {
this.formSubmit.emit(this.form.value);
}
}
export class FormControlService {
constructor() { }
public toControlGroup(controls: Array<ControlBase<any>>) {
const group: any = {};
controls.forEach(control => {
const validators: any = [];
// Required
if (control.required) {
validators.push(Validators.required);
}
// remove for brevity
group[control.key] = new FormControl(control.value || "", validators);
});
return new FormGroup(group);
}
}
我还是新手,还在学习 Angular。关于初始化异步数据时如何克服该问题的任何建议?