Hi I have a parent component that allows one to select different fields. I'm using nz-zorro's date selector and select components. For example, Date from a date selector, a couple of strings from drop down select fields etc. I've figured that you can use a a Subject event to emit changes to the child components input as and when any of the individual field selectors' callbacks are called.
It seems to me that making an event/input/output for each variable is a repetitive pattern that could be avoided by mapping all these fields I care about to one model.
My question then becomes how do I synchronize changes to any field of a model in one function or in a non code paste way....
var1DateEvent: Subject <Date> = new Subject <Date>();
var2StringEvent: Subject <string> = new Subject <string>();
Instead of having
onvar1Change(){ this.var1DateEvent.next(this.ngModelDate)}
onvar2Change(){ thos.var2StringEvent.next(this.ngModelString)}
Where the model variables are the models mapped to my UI components and onvar1Change() is the callback mapped to that UI element, the child component subscribes to these Input Observable inside its init file.
What I would like to do is have a custom model that has all these changeable fields and whenever any field of the model is changed, the UI emits an event of the entire model to the Child component. This feels like a better pattern to me but I'm not sure how to go about it as I'm new to Angular.
If you have a parent child relation in your component there is no need to use the subject observable , i suggest you to use the @Input and @Output, for synchronising the changes in your child component
var1DateEvent:any;
<your-app-selector-name [var1DateEvent]="var1DateEvent" ></your-app-selector-name
@Input() var1DateEvent;
and call the ngOnChanges() :
ngOnChanges(){
console.log('changes from parent component',var1DateEvent);
}
also you need to import Input from : import { Component, OnInit ,Input } from '@angular/core';
I hope this would help you, Thanks