Reputation: 942
Im adding subscriptions into my instance of Subscription
. How to find out how many subscriptions inside subscriptions
constant?
const subscriptions = new Subscription();
...
formKeys.forEach(key => {
subscriptions.add(
form.controls[key].valueChanges.subscribe(...)
}
full code:
Component:
@Component({
selector: 'cts-schema-template',
templateUrl: './schema-template.component.html',
styleUrls: ['./schema-template.component.sass']
})
export class SchemaTemplateComponent implements OnInit, OnDestroy {
form: FormGroup;
subscriptions = new Subscription();
_template: SchemaTemplate;
@Input()
set template(template: SchemaTemplate) {
this._template = template;
this.subscriptions.unsubscribe();
this.subscriptions = new Subscription();
this.subscriptions.add(
this.formService.bindModelToForm(this._template, this.form)
);
}
get template() {
return this._template;
}
constructor(private formBuilder: FormBuilder,
private formService: FormService
) {
this.form = formBuilder.group({
name: ['', Validators.required],
description: ['', Validators.required],
})
}
ngOnInit() {
}
ngOnDestroy(): void {
this.subscriptions.unsubscribe();
}
get nameField(): AbstractControl {
return this.form.controls['name'];
}
get descriptionField(): AbstractControl {
return this.form.controls['description'];
}
}
function bindModelToForm:
bindModelToForm(model: any, form: FormGroup, idFields: string[] = []): Subscription {
this.initForm(model, form);
if (!this.checkFieldsMatching(model, form)) {
throw new Error('FormService -> bindModelToForm: Model and Form fields is not matching');
}
const subscriptions = new Subscription();
const formKeys = Object.keys(form.controls);
formKeys.forEach(key => {
if (idFields.includes(key)) {
subscriptions.add(
form.controls[key].valueChanges.subscribe(
(newValue) => {
model[key] = newValue.id;
}
)
)
} else {
subscriptions.add(
form.controls[key].valueChanges.subscribe(
(newValue) => {
model[key] = newValue;
}
)
);
}
});
return subscriptions;
}
Upvotes: 1
Views: 232