使用 Angular 12,我想验证和检测列表中的更改。
我有一个属性网格(一个键/值对表,列出具有可编辑值的属性,但每个值都可以是不同的类型,字符串/布尔值/int/等)。
我想为该属性网格添加验证和更改检测。
应该对每个项目进行验证,并且只需要对整个列表进行更改检测(不关心更改了哪一行/项目)。
我已经建立了这样的东西:
export class InnerSetting {
key!: string;
displayName!: string;
originalValue?: string;
value?: string;
type!: PropertyTypeEnum; //string | int | boolean | ...
validation?: string;
minValue?: number;
maxValue?: number;
isNullable!: boolean
}
constructor(private formBuilder: FormBuilder) {
this.form = this.formBuilder.group({
properties: new FormArray([])
});
}
ngOnInit(): void {
this.settings.forEach(item => this.formArray.push(this.formBuilder.group(
{
key: [item.key],
type: [item.type],
name: [item.displayName],
value: [ item.value, [Validators.required, Validators.minLength(2)] ], //Depends on type and validation stuff, will be added later.
originalValue: [ item.originalValue ]
}
)));
//Not sure which of these will work, so added both for now.
this.form.valueChanges.pipe(debounceTime(500)).subscribe(changes => {
this.areChangesDetected = changes != null;
});
this.formArray.valueChanges.pipe(debounceTime(500)).subscribe(changes => {
this.areChangesDetected = changes != null;
});
}
get formArray() {
return this.form.controls.properties as FormArray;
}
在使用 a 之前Form
,我只是在使用一个InnerSetting
列表,所以请记住,我刚刚开始用表单替换列表。
该setting
属性是一个InnerSetting
对象。
<form [formGroup]="form" class="group-wrapper">
<div class="d-flex item-row" *ngFor="let setting of formArray.controls; let i = index">
<div class="item flex-fill d-flex" [ngSwitch]="setting.type" [formGroupName]="i">
<span>{{setting.name}}</span>
<select *ngSwitchCase="'boolean'" class="flex-grow-1" name="role" id="role-select" [(ngModel)]="setting.value">
<option [value]="'0'">False</option>
<option [value]="'1'">True</option>
</select>
<div contenteditable *ngSwitchDefault class="flex-grow-1" type="text" [id]="setting.key" [innerText]="setting.value"></div>
</div>
<button class="remove-relation" (click)="reset(setting)">
<fa-icon [icon]="faUndo"></fa-icon>
</button>
</div>
</form>
问题
因为我需要根据设置类型(布尔值、字符串、数字等)显示不同的元素。我如何从formArray.controls
?
另外,如何绑定到非标准输入控件,例如我div
的 with a contenteditable
?
编辑
我注意到这formArray.controls
是一个数组FormGroup
,我可以访问this.formArray.controls[0].controls['name'].value
.
现在的问题是根据类型将该控件设置为字段(选择或 div 或输入)。