Issue
Still getting my head around observables and I'm trying to do something I'm pretty sure is possible.
Our application has a class variable called references, which is an array of type FormArray.
references = new FormArray([]);
This particular form is fairly standard CRUD, where the references array is populated from a service with an array of objects, and the forms are patched with the return values.
I'm working on a story where I have to get the reference that was created first, and then bubble that value up to a parent component. And I have it working, using an event emitter. On each CRUD function, I pass the references to a method that sorts them and then finds the oldest one.
setOldest(references: FormArray): void {
const firstBolRef = filtered.reduce((a, b) => new Date(a.value.Created) < new Date(b.value.Created) ? a : b);
this.firstBOLChanged.emit(firstBolRef.value);
}
I feel like there's a way to set up an observable that watches the references array and then outputs the value instead of calling the setOldest function on every event. I haven't found an example that's doing quite what I'm trying to do.
Solution
I usually subscribe to the changes of a form field (or to the whole form). I don't know it is going to work just for an FormArray control (that is not inside a form), but you can try this:
Once you have inicialized references with references = new FormArray([]); do this:
this.references.valueChanges.pipe(tap((values) => {console.log(values);}));
If you get by console a value everytime that this.references changes, you only have to change the console.log() instruction by the code you want.
Answered By - Juan Vicente Berzosa Tejero
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.