Angular 扩展FormGroup并在其中处理订阅
我通常通过以下方式创建表单:Angular 扩展FormGroup并在其中处理订阅,angular,angular-reactive-forms,unsubscribe,Angular,Angular Reactive Forms,Unsubscribe,我通常通过以下方式创建表单: export class ModelXFormGroup extends FormGroup { constructor() { super({ property1: new FormControl() }); } getRawValue(): ModelX { return super.getRawValue(); } patchValue(template: ModelX) { super.pa
export class ModelXFormGroup extends FormGroup {
constructor() {
super({
property1: new FormControl()
});
}
getRawValue(): ModelX {
return super.getRawValue();
}
patchValue(template: ModelX) {
super.patchValue();
}
get property(): FormControl {
return this.get('property') as FormControl;
}
}
如果我需要根据其他属性将属性设置为“禁用”,那么在构造函数中,我可以执行以下操作:
this.property1.valueChanges(newValue -> {
if(newValue){
this.property2.disabled();
} else{
this.property2.enabled();
}
});
但我不知道我怎么能杀死那些订阅。。。
我的意思是,我不能在这里使用Ngondestory并调用此.subscription.unsubscripte()
有什么方法可以在表单中执行此操作吗
因为我认为唯一的替代方法是在表单中使用一个方法来手动取消所有属性的注册
组成部分:
onDestroy {
this.form.unSuscribe();
}
但是我想让它对组件透明。您可以使用
takeUntil
private _destroyed = new Subject<boolean>();
ngOnInit() {
// property 1
this.property1.valueChanges
.pipe(
takeUntil(this._destroyed) // specify takeUntil
)
.subscribe(value => { ... })
// property 2
this.property2.valueChanges
.pipe(
takeUntil(this._destroyed)
)
.subscribe(value => { ... })
}
ngOnDestroy() {
this._destroyed.next(true); // will unsubscribe all property that specify takeUntil
this._destroyed.unsubscribe();
}
稍后在组件中,您可以在ngondestory
ngOnDestroy() {
this.myModelXForm.unsubscribe();
}
嘿,实际上我一直在处理类似“MyNeedForm”的方法。 因此,为了在我的类中处理订阅,它扩展了FormGroup: 首先在类的头部初始化订阅数组:
private subscriptions: Subscription[];
在里面添加订阅内容,例如:
const valueChangesControl = valueChangeControl.valueChanges.subscribe(x => console.log("Value: ", x));
this.subscriptions.push(valueChangesControl);
编写您的函数以将其全部剪切:
cutSubscribtions() {
this.subscriptions.forEach(sub => sub.unsubscribe());
}
最后,在实例化表单的组件的OnDestroy()生命周期中,调用函数:
ngOnDestroy() {
console.log("call destroy()");
this.testForm.cutSubscribtions();
}
看看这个例子:我认为我不能在普通类中实现OnInit&OnDestroy。它应该是一个组件,但正如我所说,我为每个表单创建了特定的类。我认为不应该在类中实现valueChanges,因为它是应该在组件中实现的视图逻辑的一部分。它实际上不是视图的一部分,“disable”是表单的一个属性。form类独立于组件。@user2992476这里使用表单的有趣方法当然可以将表单声明保留在组件中。但是我喜欢为每个字段表单创建getter,这样我就不需要通过formControlName或form.get('fieldPropertyAsString')进行访问,这意味着将字段名称作为硬编码字符串传递。
ngOnDestroy() {
console.log("call destroy()");
this.testForm.cutSubscribtions();
}