Pipe operator not working when combining with async pipe in template for valuechanges observable

Karthikeyan

I am trying to capture user inputs and perform some business logic depending upon the inputs and bind the resulting data back to the form element. I hook into form valuechanges observable and perform my custom logic and bind the result to template.

I am trying to avoid subscribing from component and do it from template using async pipe as shown below. But if I am not subscribing from the component, logic is not triggering.

From my understanding since async pipe will subscribe to the observable, from component the pipe operation logic should work fine but is is not getting called unless I do another subscribe as shown below, can any one help me why it is not triggering the pipe operator logic since I already subscribed using async pipe in the template, please ? Thanks.

I tried moving the logic to ngAfterViewChecked hook still not working, if I subscribe from component it is working but I want to avoid multiple subscription.

import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Observable } from 'rxjs';
import { tap, startWith } from 'rxjs/operators';

@Component({
    selector: 'app-check-value-changes',
    templateUrl: './check-value-changes.component.html',
    styleUrls: ['./check-value-changes.component.scss']
})
export class CheckValueChangesComponent implements AfterViewInit {
    @ViewChild('form') form: NgForm;
    valueChanges$: Observable<any>;

    ngAfterViewInit() {
        this.valueChanges$ = this.form.valueChanges;
        // Not Working
        this.valueChanges$.pipe(
            tap((c) => console.log(`Async pipe Subscribe ? - ${JSON.stringify(c)}`))
            // other business logic here
        );

        // Working fine
        this.valueChanges$.pipe(
            tap((c) => console.log(`Explicit Subscribe - ${JSON.stringify(c)}`))
            // other business logic here
        ).subscribe();
    }
}
<span *ngIf="valueChanges$ | async as value">
    {{ value | json }}
</span>
<form #form="ngForm">
    <input type="text" name="txtName" ngModel>
</form>
Karthikeyan

Turns out to be a simple fix, when I combined the observable initialization and pipe operation statements together in a single line everything works fine.

In my original code even though I did my pipe operation in valueChanges$ observable I didn't mutate the original observable and eventually created another observable which of-course needs another subscription to emit the values.

Fixed component code :

import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Observable, Subject } from 'rxjs';
import { tap } from 'rxjs/operators';

@Component({
    selector: 'app-check-value-changes',
    templateUrl: './check-value-changes.component.html',
    styleUrls: ['./check-value-changes.component.scss']
})
export class CheckValueChangesComponent implements AfterViewInit {
    @ViewChild('form') form: NgForm;
    valueChanges$: Observable<any>;

    ngAfterViewInit() {
        this.valueChanges$ = this.form.valueChanges.pipe(
            tap((c) => console.log(`Async pipe Subscribe ? - ${JSON.stringify(c)}`))
        );
    }
}

Dev Tools

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Observable with Async Pipe in template is not working for single value

Angular template binding with Observable async pipe issue

Template binding with function return Observable and async pipe

Template does not render observable using async pipe

Access Observable in the Template without using the Safe Navigation Operator and Async Pipe Everytime

Safe navigation operator on an async observable and pipe in Angular 2

Performance of using same observable in multiple places in template with async pipe

How to initialized an observable for async pipe in the template trying to mimic an assignation in the subscription?

Why is observable subscribe() not triggered while the async pipe in the template properly refreshing?

[Angular]: Tap on to an observable that has been used in template with async pipe

Async pipe not working with Subject

Angular 6 - rxjs pipe not working on valueChanges

Reusing Async Pipe (Observable) Output

How to async pipe an observable in Angular

Async pipe and subscribe on the same Observable

Observable Async Pipe Not Returning Values

Async Pipe failing when linked to newly created observable

Angular Async Pipe and the 'delay' operator

why observable pipe is not working in component?

using async pipe to the property on template

Using ngModel with async pipe in template

Angular replace pipe operator is not working

Rxjs timeout() operator not working in pipe

spyOn not working with async pipe in Angular

Angular async pipe not working with fromEvent

FormControl ValueChanges Pipe Not Firing

Observable seems to persist despite in pipe subscribed by async pipe

Pipe operator that returns a boolean valued observable

Using pipe operator in function which returns Observable

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive