我不知道这是否可行,但我建立了一个动态表单组件,该组件运行得很好,并且我可以通过配置文件控制许多项目。
我无法控制的一项是输入字段的宽度,我尝试了很多方法,但似乎没有一种有效。即在创建表单控件时在组件中设置宽度等
有人知道我想做的事实际上是否可以实现,并且可以为我指明正确的方向。
模板代码
<div fxLayout="row">
<div [formGroup]="formGroup" fxLayoutAlign="start" fxLayoutGap="10px">
<div *ngFor="let form_elem of formTemplate">
<div *ngIf="form_elem.visible === 'true'">
<mat-form-field>
<mat-label>{{ form_elem.label }}</mat-label>
<input
matInput
type="text"
formControlName="{{ form_elem.name }}"
class="{{ form_elem.width }} "
/>
</mat-form-field>
</div>
</div>
</div>
</div>
打字稿代码
import {
ChangeDetectionStrategy,
Component,
EventEmitter,
Input,
Output
} from "@angular/core";
import { FormGroup, FormControl } from "@angular/forms";
@Component({
selector: "fw-form-array-item",
templateUrl: "./form-array-item.component.html",
styleUrls: ["./form-array-item.component.scss"],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class FormArrayItemComponent {
@Output() remove = new EventEmitter<FormGroup>();
@Input() formGroup: FormGroup;
@Input() formTemplate: any;
constructor() {}
ngOnInit() {
let group = {};
this.formTemplate.forEach(input_template => {
group[input_template.label] = new FormControl('');
});
}
}
表单模板配置文件
export class OrdersProductsFormTemplate {
config = [
{
type: "textBox",
label: "id",
name: "id",
width: "50%",
justify: "left",
visible: 'true',
disabled: true
},
{
type: "textBox",
label: "Name",
name: "name",
width: "100%",
justify: "left",
visible: 'true',
disabled: false
},
{
type: "textBox",
label: "Currency",
name: "currency",
width: "100%",
justify: "left",
visible: 'true',
disabled: false
},
{
type: "textBox",
label: "Retail",
name: "retailPrice",
width: "100%",
justify: "left",
visible: 'true',
disabled: false
},
{
type: "textBox",
label: "Supplier Price",
name: "supplierPrice",
width: "100%",
justify: "left",
visible: 'true',
disabled: false
}
];
}
您可以使用[ngStyle]添加内联宽度和数组中的属性宽度,例如
<input matInput type="text"formControlName="{{ form_elem.name }}"
[ngStyle]="'width':'{{ form_elem.width }}' " />