When a new form object is assigned, the outputFromObservable breaks due to Angular typed form events

Apologies for the lengthy title.

In one of my components, I have an Angular v18 typed form that exposes the ValueChangeEvent as an output event using the outputFromObservable() function:

export class SessionEditFormComponent {
  private fs = inject(SessionFormService);
  sessionForm: FormGroup<SessionForm> = this.fs.getDefaultForm();
  session = input.required<ProgramSession>();
  onFormValueChange = outputFromObservable(
    this.sessionForm.events.pipe(
      filter((e) => e instanceof ValueChangeEvent),
      debounceTime(1000),
      distinctUntilChanged()
    )
  );

  constructor() {
    effect(() => {
      if (this.session().title !== undefined) {
        console.log('session effect', this.session());
        this.fs.patchForm(this.session());
      }
    });
  }
}

The custom function "fs.patchForm()" takes a custom object named session, constructs a new form group with multiple nested form arrays, and returns a NEW form which is then assigned to the component's sessionForm property. The parent component listens for onFormValueChange events like so:

(onFormValueChange)="onFormChange($event)"

THE ISSUE:

After reassigning the form in the signal/constructor effect, it disrupts the onFormValueChange observable. The changes are no longer emitted. Removing the effect results in all form events being emitted correctly.

Could someone help me ensure that the change events continue to emit even after assigning a new form to the sessionForm property?

Thank you!

Answer №1

In order to reallocate the form, you must utilize the form as a subject or indicator, depending on your preference.

updatedForm$: Subject<FormGroup<UpdatedForm>> = new BehaviorSubject(this.us.getDefaultForm());
  onChangeFormValue = dataFromStream(
    this.updatedForm.pipe(
      switchMap(form => form.events),
      filter((e) => e instanceof ValueChangeEvent),
      debounceTime(1000),
      distinctUntilChanged()
    )
  );
replaceForm() {
  const freshForm = ...;
  this.updatedForm$.next(freshForm);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on sorting a FileList object selected by a directory picker in JavaScript/TypeScript

I need to filter or eliminate certain files from a FileList object that I obtained from a directory chooser. <input type="file" accept="image/*" webkitdirectory directory multiple> Within my .ts file: public fileChangeListener($event: any) { let ...

Transforming JavaScript into TypeScript within an Angular 4 component class

Here is the Javascript code I currently have. I need to convert this into a component class within an Angular component. As far as I understand, the Character.prototype.placeAt() code is used to add a new method or attribute to an existing object. In this ...

Exploring StickIt: Binding the length property from a backbone.Collection

Exploring the use of Backbone, Marionette (1.8.3), StickIt, and TypeScript to effectively bind the length of a Backbone collection in real-time as items are added or removed. As someone new to StickIt, here's my current attempt: export class SomeVie ...

Guide to personalizing the ngxDaterangepickerMd calendaring component

I need to customize the daterangepicker library using ngxDaterangepickerMd in order to separate the start date into its own input field from the end date. This way, I can make individual modifications to either the start date or end date without affectin ...

"Update your Chart.js to version 3.7.1 to eliminate the vertical scale displaying values on the left

Is there a way to disable the scale with additional marks from 0 to 45000 as shown in the screenshot? I've attempted various solutions, including updating chartjs to the latest version, but I'm specifically interested in addressing this issue in ...

Ways to activate subscriptions in type-graphql?

I'm encountering an issue with setting up subscriptions in my Apollo Server project using Express. Despite following all the steps outlined in the documentation [https://typegraphql.com/docs/subscriptions.html], I can't seem to get it working. In ...

There was an issue encountered while compiling the template for 'AppModule'

While attempting to construct an Angular 6 application, I encountered an issue when utilizing the --prod flag. ERROR in Error during template compile of 'AppModule' Expression form not supported in 'reducers' 'reducers' ...

Exploring the functionality of this TypeScript code: What's the distinction between { [key: string]: string }[] and { prop1: string, prop2: string }[]

Below is the code I am currently working with: get tags(): { [key: string]: string }[] { let tags: { [key: string]: string }[] = []; if(this.tags) { Object.keys(this.tags).forEach(x => { tags.push({ prop1: this.tags[x], prop2: g ...

Rendering an Angular page with data using Node.js

I have a scenario for my website where users need to input a URL with a parameter (an ID) and receive back the corresponding page containing information from the database. I am using Angular4 but I am unsure of how to achieve this. It's straightforwa ...

What is the method for activating a validation of a child component from a parent component during the submission process in Angular 4

I have a scenario where I have multiple child form components included in a parent component. Each child component contains its own form group, and I need to validate all child forms when the user clicks on submit in the parent form. How can I trigger val ...

Setting up Microsoft Clarity for your Angular app on localhost is a simple process

Currently, I am attempting to set up Microsoft Clarity on my Angular app to run on localhost. After creating a new project on the Microsoft Clarity portal and specifying the URL as localhost (I also tried using localhost:4200</code), I copied the scrip ...

When trying to use ngModel with Angular, an error occurs where the property 'selected' cannot be created on a string

I'm currently attempting to utilize [(ngModel)] in the following manner: <div class="items"> <tbody> <tr *ngFor="let info of this.information"> <td> <input type="checkbox" [(ngModel)]="this.info.n ...

How can a component properly accept a class as an input and integrate it with its own classes?

Consider a scenario where a component dynamically assigns values to the class attribute of its host element based on specific runtime conditions. For instance, let's analyze this TextBox component that sets class values depending on the readonly and ...

Angular2 error: "missing exported member 'bootstrap'"

Upon opening my Atom editor, I encountered the following message: The issue of 'Module '"C:/express4/node_modules/@angular/platform-browser-dynamic/index"' not exporting member 'bootstrap' raised at line 2 col 10 This warning a ...

NextJS middleware API receives an uploaded image file form, but the request is undefined

Currently, I'm utilizing NextJS to handle form data processing and database uploads, with a pit stop at the NextJS API middleware for image editing. pages/uploadImage.tsx This is the client-side code handler. ... async function handleImageUpload(imag ...

Best location for the classes of the Domain Model suggested

Currently, I am delving into Angular 2 and making use of angular-cli for creating components and services. Adhering to the directory structure suggested by angular-cli (view screenshot below), I am uncertain about where to include domain model objects like ...

Defining a property of an object within a Vue Class

If I were to write it in JavaScript version: export default { data() { return { users: {} } } } However, when using a class style component with vue-property-decorator: @Component export default class Login extends Vue { public title ...

having difficulties sorting a react table

This is the complete component code snippet: import { ColumnDef, flexRender, SortingState, useReactTable, getCoreRowModel, } from "@tanstack/react-table"; import { useIntersectionObserver } from "@/hooks"; import { Box, Fl ...

Ways to detect button click in a separate component

I am working with an Angular app that consists of two components: a navbar component and a display component. The navbar component has a search button that, when clicked, searches for the entered name and displays the details in the display component. I ne ...

Turn off the `noImplicitAny` TypeScript rule for a specific line of code

With "noImplicitAny": true enabled in my tsconfig.json, I encountered the TS7053: Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{}' error within my code space ...