After the switchMap is applied, valueChanges does not emit values when typing in the input field

I am puzzled by the issue in my code found at this link. I am using widgetNameForm$ to send data to a child component. However, even though switchMap should switch to the valueChanges stream and emit values when typing in an input field, it is not working as expected. Previously, I had a different code structure with nested subscriptions, but I prefer a more reactive approach as shown on StackBlitz below:

 this.widgetName$.subscribe(val => {
  this.widgetNameForm = this.formBuilder.group({
    name: [val, {validators: Validators.required}]
  });

  this.widgetNameForm.valueChanges.pipe(
    takeUntil(this.destroy$)
  ).subscribe(val => console.log('it emits value on typing', val));
})

Answer №1

You currently have 2 different subscriptions:

  • one in the constructor
  • one in the template using the async pipe

The issue lies in each subscription receiving a separate instance of a FormGroup. This means that the instance subscribed to in your controller is not the one passed to the child component and bound to the form, resulting in no valueChanges being emitted.

To address this problem, you can share a single subscription by utilizing the shareReplay operator:

this.widgetNameForm$ = this.widgetName$.pipe(
  map(val => this.formBuilder.group({ name: [val, {validators: Validators.required}] })),
  shareReplay() // <---
);

Take a look at this StackBlitz. Notice how the "instance id" is displayed in the input field. By commenting out the shareReplay() line, you will observe having 2 instances, but with it, you will only have one.

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

How to automatically set member fields for string literal types in Typescript

Imagine having the following classes: class Foo { type: "foo" constructor(public id: number) {} } class Bar { type: "bar" constructor(public id: number) {} } type SomeUnion = Foo | Bar // (x : SomeUnion).type will have the type "foo" | "bar" Wh ...

Having trouble getting Angular2 tutorial animations to work in IE11?

After successfully setting up a local development environment using the Angular2 tutorial with the quick start seed [1], I decided to experiment with animations. Following a modified version of an example from [2], my app.component.ts now toggles backgroun ...

New to TypeScript: Encounter a compilation error while launching Apollo Server and attempting to resolve a promise

Seeking assistance with starting an Apollo server in a TypeScript project utilizing Express. The code snippet for my app.ts is displayed below. Upon execution, I encounter the following error: Argument of type '(value: unknown) => void' is not ...

Compiler is unable to comprehend the conditional return type

I've done some searching, but unfortunately haven't been able to find a definitive solution to my issue. Apologies if this has already been asked before, I would appreciate any guidance you can offer. The problem I'm facing involves a store ...

Changing the value within a nested object dynamically in Angular 6 during execution

Currently working with angular 6 and have a method like this: public Save(): void { this.data.station.parkingSlot.forEach(p => { if(p.isAvailable){ p.isAvailable = false; this._carService.addCar(this.data); return true; ...

waiting for the import statement in a React/NextJS/Typescript project to resolve

While working on my node.js development server, I encountered a problem with the following code: import { useRouter } from 'next/router' import nextBase64 from 'next-base64'; const Load = () => { const router = useRouter() co ...

Angular encountered an error while attempting to manage a base service that was not defined

My service involves extending a base service to handle error data effectively. For instance import { CurrentUserService } from './current-user.service'; import { CONFIG } from './../shared/base-urls'; import { BaseServiceService } fro ...

What is the method to retrieve the name of a derived class from a base class?

Can we retrieve the name of a derived class from within the base constructor? class Entity { constructor() { // How can we access and log the class name here? console.log('a') } } class a extends Entity {} new a() ...

Top method for storing images and videos with Angular and a web API

As a newcomer to web.api, I am looking to store images/videos in a database. I have three options: Convert it to base-64 on the front end, send it to the back end, then convert it back to its original form and save it to a folder. Instruct the front ...

Angular's FormGroup for reactive forms is a powerful feature that allows for

Why am I unable to type in the input field before setting a value? html <form action="" [formGroup]="titleForm"> <input class="note-title" type="text" formControlName="title"> </form> ...

Can SystemJS, JetBrains IntelliJ, and modules be combined effectively?

Looking for some clarification on the functionality of module includes and systemJS within an Angular2 app structure. I have set up a basic Angular2 app with the following layout: -app |-lib (contains shims and node libraries) |-components |-app |-app. ...

Tips for correctly specifying the types when developing a wrapper hook for useQuery

I've encountered some difficulties while migrating my current react project to typescript, specifically with the useQuery wrappers that are already established. During the migration process, I came across this specific file: import { UseQueryOptions, ...

Could you please explain the significance of /** @docs-private */ in Angular's TypeScript codebase?

After browsing through the @angular/cdk code on GitHub, I came across a puzzling "docs-private" comment. Can anyone explain its significance to me? Link to Code https://i.sstatic.net/Z47Xb.png * In this base class for CdkHeaderRowDef and CdkRowDef, the ...

Google Places Autocomplete with Angular 4 Material Design Integration

I'm looking to incorporate Google Places (autocomplete field) into my Angular 4/5 app that is styled using the Material UI framework. While I did come across a module here, it doesn't quite meet my needs as I am unable to style the input box wit ...

Guide to sorting through an array for a particular keyword

In my array, I have objects with IDs and names. For example: { [ { "id": 1, "name": "this is book", }, { "id": 2, "name": "this is a test book", }, { "id": 3, "name": "this is a desk", } ] } Now, let's say I want ...

What functionality does the --use-npm flag serve in the create-next-app command?

When starting a new NextJS project using the CLI, there's an option to use --use-npm when running the command npx create-next-app. If you run the command without any arguments (in interactive mode), this choice isn't provided. In the documentati ...

Displaying the value only when the condition is met in Angular

I am working on a feature to display a list of job postings made by HR in an Angular HTML page. The requirement is that when a HR logs in, they should only see the jobs they have posted, not all the jobs posted by all HRs. I plan to accomplish this by comp ...

What is the command line method for running ESLint in flat configuration?

When using the flat config for eslint.config.js, how can I lint *.js files recursively from the command line? 1 In the past with eslintrc.js or eslintrc.json, I have used npx eslint . --ext .js, as mentioned here. Up until now, it has always worked withou ...

Using Typescript and Angular 5: A guide on trimming an array when its length is less than 5

What is the method to shorten an array if it has less than 5 elements? This is my JSON data: [ { "type": "aaa", "values": [ { "risk": "A" }, { "risk": "Q" }, { "risk": "M ...

After updating Bootstrap, the build task encountered an error when it was unable to locate the node.exe needed to run the TypeScript compiler

After developing an ASP.Net MVC web application that was almost completed, I decided to update Bootstrap using the NuGet package manager to the latest stable version 4.3.1. The update process went smoothly, but unfortunately, I encountered errors after mig ...