Angular 角度动态表单:以编程方式更新值是一种不好的做法吗?
我已经实现了一个通用的动态表单组件:Angular 角度动态表单:以编程方式更新值是一种不好的做法吗?,angular,typescript,angular-forms,Angular,Typescript,Angular Forms,我已经实现了一个通用的动态表单组件: @Component({ selector: 'dynamic-form', templateUrl: './dynamic-form.component.html' }) export class DynamicFormComponent implements OnInit, OnChanges { @Input() inputs: InputBase<any>[] = []; @Input() submitL
@Component({
selector: 'dynamic-form',
templateUrl: './dynamic-form.component.html'
})
export class DynamicFormComponent implements OnInit, OnChanges {
@Input() inputs: InputBase<any>[] = [];
@Input() submitLabel: string;
@Input() globalValidator: ValidatorFn | undefined;
@Output() onSubmit: EventEmitter<any> = new EventEmitter<any>();
@Output() onChanges: EventEmitter<any> = new EventEmitter<any>();
@Output() onValid: EventEmitter<boolean> = new EventEmitter<boolean>();
private wasValid: boolean = false;
form: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
//Let's get the needed controls to create a FormGroup
this.form = this.generateFormGroup();
}
ngOnChanges() {
this.form = this.generateFormGroup();
}
private generateFormGroup(): FormGroup {
let group: any = {};
this.inputs && this.inputs.forEach(ib => {
ib.addtoFormGroup(group);
});
let form: FormGroup;
if (this.globalValidator) {
form = this.fb.group(group, { validator: this.globalValidator });
} else {
form = this.fb.group(group);
}
form.valueChanges.subscribe(data => {
if (this.form.valid !== this.wasValid) {
this.wasValid = this.form.valid;
this.onValid.emit(this.wasValid);
}
this.onChanges.emit(this.form.value);
});
return form;
}
submit() {
this.onSubmit.emit(this.form.value);
}
isValid(): boolean {
return this.form.valid;
}
getValue() {
return this.form.value;
}
}
现在df输入组件如下(简化):
这种做法不好吗?我在更新我的组件状态时遇到了很多问题,我正在尝试保持智能哑组件的方法,但这对我来说不是一件容易的任务您可能希望创建一个
验证服务或类似的服务,并将您所有的自定义验证程序放在那里
例如,我有:
import { Injectable } from '@angular/core';
import { FormGroup, AbstractControl } from '@angular/forms';
import { shouldMatch } from './should-match';
@Injectable()
export class Validation {
shouldMatch(...props: string[]) {
return (group: FormGroup): any => shouldMatch(group, ...props);
}
}
should-match.ts:
import { FormGroup } from '@angular/forms';
export function shouldMatch(group: FormGroup, ...props: string[]): any {
const ctrls = group.controls;
const len = props.length;
for (let i = 1; i < len; i++) {
if (ctrls[props[0]]) {
if (ctrls[props[0]].value !== ctrls[props[i]].value) {
return {invalid: true};
}
} else {
throw new Error(`The property '${props[0]}' passed to 'shouldMatch()' was not found on the form group.`);
}
}
return null;
}
这是一个不错的做法。但是,如果您想处理验证,请查看angular指南。我自己做的日期验证器是这样的。在这里查看一下。对于处理,我想让它们在formGroup中保持更新,而不是让angular从输入元素获取它们。为什么不使用NgModel和NgModelChange=updateModel($event)?或(keyup)=updateModel($event)
@Component({
selector: 'df-input',
templateUrl: './input.component.html',
styleUrls: ['./input.component.css']
})
export class InputComponent implements OnInit, OnChanges,DoCheck {
@Input() input: InputBase<any>;
@Input() form: FormGroup;
private wasValid: boolean = false;
differ: any;
constructor(private differs: KeyValueDiffers) {
}
ngOnInit() {
this.differ = this.differs.find(this.input).create();
if (this.input.controlType === 'dropdown') {
let configuration: InputDropdownConfiguration<any>= (this.input as InputDropdownConfiguration<any>);
if (configuration.options && configuration.options.length===1) {
if (this.form) {
(this.form.controls[this.input.key] as AbstractControl).setValue(configuration.options[0].value)
}
}
}
}
ngOnChanges() {
this.ngOnInit();
}
ngDoCheck() {
var changes = this.differ.diff(this.input);
}
get isValid(): boolean {
if (this.form && this.form.controls && this.form.controls[this.input.key]) {
return this.form.controls[this.input.key].valid || !this.form.controls[this.input.key].touched;
}
return true;
}
}
<div [formGroup]="form" class="form-group" [class.has-error]="!isValid">
<label *ngIf="input.label" [attr.for]="input.key" class="control-label col-sm-{{labelWidth}}">
<ng-container *ngIf="input.isRequired">* </ng-container>{{input.label | translate}}
</label>
<div [ngSwitch]="input.controlType" class="col-sm-{{inputWidth}}">
<input *ngSwitchCase="'text'" class="form-control" [formControlName]="input.key" [type]="input.type"
[name]="input.key" [readonly]="input.readonly" placeholder="{{input.placeholder |translate }}">
<select *ngSwitchCase="'dropdown'" [formControlName]="input.key" class="form-control">
<option *ngFor="let opt of options" [selected]="input.value == opt.value" value="{{opt.value}}">{{opt.text | translate}}</option>
</select>
</div>
<div class="help-block col-md-10 col-md-offset-1" *ngIf="!isValid" [hidden]="!isValid">{{input.errorMsg | translate}}</div>
</div>
form.controls[input.key].setValue(<new_value>)
import { Injectable } from '@angular/core';
import { FormGroup, AbstractControl } from '@angular/forms';
import { shouldMatch } from './should-match';
@Injectable()
export class Validation {
shouldMatch(...props: string[]) {
return (group: FormGroup): any => shouldMatch(group, ...props);
}
}
import { FormGroup } from '@angular/forms';
export function shouldMatch(group: FormGroup, ...props: string[]): any {
const ctrls = group.controls;
const len = props.length;
for (let i = 1; i < len; i++) {
if (ctrls[props[0]]) {
if (ctrls[props[0]].value !== ctrls[props[i]].value) {
return {invalid: true};
}
} else {
throw new Error(`The property '${props[0]}' passed to 'shouldMatch()' was not found on the form group.`);
}
}
return null;
}
this.form = this.fb.group({
paswords: this.fb.group({
password: [null, Validators.required],
passwordConfirmation: [null, Validators.required]
}, {validator: this.validation.shouldMatch('password', 'passwordConfirmation')}
})