如何解决NGX-FORMLY动态形式的hideExpression
我正在尝试在ngx中正式构建动态表单,但是在保持关注点分离的同时却无法正常工作。这通常可以正常工作,但是问题正在模型中传递,当从api中预先填充表单时,hide表达式无法获得更新的模型
formFactory.ts
import { Injectable } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { FormlyFieldConfig } from '@ngx-formly/core';
import { of } from 'rxjs';
@Injectable()
export class TaskFormFactory {
private model: any = {};
fields: FormlyFieldConfig[];
form = new FormGroup({});
constructor() {}
get formModel() {
return this.model;
}
public formFields() {
return [
{
key: 'name',type: 'input',templateOptions: {
label: 'Task name',placeholder: 'Task name',description: '',required: true
},},{
key: 'kpi_type',type: 'select',templateOptions: {
label: 'Time allowance',placeholder: 'Time allowance',required: true,options: [
{ value: 1,label: 'Minutes' },{ value: 2,label: 'Plants per hour' },{ value: 3,label: 'Crates per hour' }
],{
key: 'kpi_time',hideExpression: () => {
console.warn('hideExpression',this.model);
return (this.model['kpi_type'] !== 1);
},templateOptions: {
type: 'number',label: 'Minutes',placeholder: '',...
MyComponent.ts
@ViewChild(FormMasterComponent,{ static: false }) formComponent: FormMasterComponent;
constructor(
private activatedRoute: ActivatedRoute,private loadingStateService: LoadingStateService,private apiService: ApiService,private formFactory: TaskFormFactory
) {
this.model = this.formFactory.formModel;
this.fields = this.formFactory.formFields();
}
ngAfterViewInit() {
if(!this.isCreateMode) {
this.loadData(this.uuid);
}
}
// if loadData happens then the hideexpression breaks
loadData(uuid?) {
const serviceCfg = this.serviceConfig;
this.loadingStateService.setLoadingState(LoadingState.Loading);
this.apiService.services(serviceCfg).subscribe((res) => {
if (typeof res['content'] !== 'undefined') {
this.model = res['content'].filter(o => {
return o.uuid === this.uuid;
})[0];
this.formComponent.patchModel('kpi_type',this.model['kpi_type']);
}
this.loadingStateService.setLoadingState(LoadingState.Loaded);
});
}
formmaster.component(只是一个包装器) ... 公共patchModel(键,值){ this.form.get(key).patchValue(value); } ...
<form [formGroup]="form" (ngSubmit)="onSubmit(model)">
<formly-form
[form]="form"
[fields]="fields"
[model]="model"
(modelChange)="onModelChange($event)"
>
</formly-form>
<div class="form-actions">
<button
mat-flat-button
type="button"
color="warn"
[disabled]="loading"
class="discard-button"
(click)="onCancelClick()">
discard
</button>
<ng-container *ngIf="unsavedChanges">
<span class="unsaved-changes-message">
<mat-icon>sync_problem</mat-icon>
<small>Unsaved Changes.</small>
</span>
</ng-container>
<button
type="submit"
class="btn btn-default"
type="submit"
mat-flat-button
color="primary"
[disabled]="canSave"
>
Submit
</button>
</div>
</form>
</div>
0 个答案:
没有答案
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。