Is it possible to update a reference to an Observable within an Angular Template?

Is it possible to update the source of an Observable referenced in an Angular template?

For instance, let's say we have this snippet in the template.

  {{ ( progress$ | async ) | date:'mm:ss'}}

And we wish to modify the Observable that $progress is linked to?

Is there a way to achieve this?

I conducted a simple experiment on Stackblitz utilizing setTimeout to showcase my intention.

https://stackblitz.com/edit/stackblitz-starters-qxxkg9?file=src%2Fmain.ts

The code responsible for changing the reference can be found in ngOnInit:

    setTimeout(() => {
      this.progress$ = of(0);
    }, 5000);

    setTimeout(() => {
      this.progress$ = interval(1000).pipe(map((c) => c * 1000));
    }, 8000);

The purpose of progress$ is to indicate how long a song has been playing. If the song stops, then progress$ should show 0. If play is resumed, then it should restart the timer...

One potential approach could be to continually pipe the Observable through function streams that modify the state accordingly?

I attempted to alter the pipe stream in this demonstration after 5 seconds, but Angular continues to render the original stream...

  ngOnInit() {
    setTimeout(() => {
      this.progress$.pipe(map((c) => 0));
    }, 5000);

Answer №1

Your stackBlitz has been successfully updated.

Click here to view the updated stackBlitz

In order to manage the observable, it is recommended to utilize either BehaviorSubject or Subject. I have provided code example below using BehaviorSubject. By doing this, you can easily control a single subscription in your template and push updates through the subject.

export class App implements OnInit {
  private progressControl$ = new BehaviorSubject<'play' | 'stop'>('play');

  progress$!: Observable<number>;

  ngOnInit() {
    this.progress$ = this.progressControl$.pipe(
      switchMap((status) => {
        if (status === 'play') {
          return interval(1000).pipe(map((c) => c * 1000));
        } else {
          return of(0);
        }
      }),
      startWith(0)
    );

    setTimeout(() => {
      this.progressControl$.next('stop');
    }, 5000);

    setTimeout(() => {
      this.progressControl$.next('play');
    }, 8000); 
  }

  name = 'Angular';
}

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

When working with a union type in TypeScript, it is important to note that the property may

Imagine a scenario where I am dealing with two specific interfaces: interface Box { x: number y: number } and interface ColouredBox { x: number y: number colour: string } For the sake of this discussion, let's assume that the ...

The process of transitioning to a different view through a button press

How can I switch to another view by clicking a button in Aurelia? Here is my code: <button class="btn btn-success " click.delegate="save()">New item</button> Typescript configureRouter(config: RouterConfiguration, router: ...

Validation error not displaying in Angular Material's mat-chip-list with input component

I'm currently encountering a peculiar problem with using mat-chip-list with inputs. My form group consists of two form controls: contacts and name. this.form = this.formBuilder.group({ name: ['', [Validators.required]], contactIds: ...

Displaying elements based on the selected mat-radio-button

I'm struggling with the logic to show and hide elements based on the selected radio button. Here's my current pseudocode: <mat-radio-button [value]="0">BUTTON A</mat-radio-button> <mat-radio-button [value]="1&quo ...

Refine the primary list by narrowing it down according to a secondary list

I created a filterList function to compare a mainList with a subList1. The function's goal is to identify the elements in the main list that are not present in subList1 and store them in subList2. public filterList(mainlist: Selectitem[], subList1: S ...

Having trouble with ng-repeat in AngularJS after including Angular 17 web components to index.html?

<select ng-if="!isOtherRemarkSelected" class="form-control m-1" ng-model="selectedRemark.value" ng-change="handleRemarks()"> <option value="">Select Remarks</option> <op ...

Switch from flexbox layout to begin on the next column within the same row

I am attempting to create a CSS layout where, after a specific element like :nth-child(6), the elements will break and form a separate column within the same row. The parent element should split into 2 columns after every 6th element in the same row, then ...

Employing ngModel in an option dropdown

I am having trouble passing an attribute from an API call to a submit function. I suspect it might have something to do with either the option select or how the input is being formatted. Encountering the error Error: No value accessor for form control wit ...

Ways to verify if a value corresponds to a particular data type

Is there a more elegant way for TypeScript to check if a value matches a specific type without actually invoking it, instead of the method described below? Consider the following example: import { OdbEventProcessorFunc } from "./OdbEventProcessor&quo ...

Angular application seamlessly connects with Nodejs application

In my Node.js application, I utilized Express generated by express generator and implemented handlebars as the view engine. The application operates smoothly on port 3000. The defined routes in Express include: ... app.use('/', index); app.use( ...

Tips for providing all props to a React component while still including necessary props specified in an interface

Am I overlooking something or is this a different issue altogether? import * as React from 'react'; interface Props { value: string; } const MyComponent = (props: Props) => { const { value, ...rest } = props; return ( & ...

Is it best practice to use the AngularFirestoreCollection for updating Firestore items in AngularFire?

Within my application, I have a list that necessitates the use of an "or" condition. However, according to the documentation: "In this case, you should create a separate query for each OR condition and merge the query results in your app." Consequently ...

Is there a way to utilize useTranslate as a utility function rather than a component?

Currently utilizing Next.js and exploring text translation using the 'next-translate/useTranslation' feature. To ensure only translated strings are displayed, I have implemented a function that checks if the string exists in my translation JSON ...

Incorporating angular2 with fullpagejs requires loading fullpage js after successfully binding data within Angular

Trying to incorporate fullpage js features into Angular2 has been a challenge for me. The issue arises when I have multiple sections on my page, with one section having child sections generated through JSON data using template binding. For example, the "se ...

Angular 5 interception mechanisms

I have been trying to set up interceptors in my Angular 5 project, but unfortunately they are not working. I injected the interceptor in the file app.module.ts, however, I am still encountering errors. Additionally, I added a console.log statement in the i ...

Fast + Vue3 + VueRouter Lazy Load Routes According to Files

I am currently working on implementing Domain-Driven Design (DDD) to Vue, and the project structure looks like this: src - App - ... - router - index.ts - Dashboard - ... - router - index.ts - ... The goal is for src/App/router/index.ts to ...

Creating a Tree Hierarchy with Angular 4 FormArray

Looking for a demonstration on how to effectively utilize FormArray with a Tree Structure? I am currently working on implementing inline editing for a hierarchical system Although I have managed to make it functional for the initial level, I am facing ch ...

Having trouble installing npm package in Angular project

After cloning my project from GitLab, I encountered an issue while trying to install the NPM packages. When I ran npm install, an error popped up: https://i.stack.imgur.com/WNT5s.png Upon checking the log file, I found the following error message: 3060 ...

Angular: Where does the problem lie - with the application or the deployment?

Currently, I am in the process of creating my own personal website using Angular(v4+). I understand that Angular may seem like a complex framework for a simple website, but I am using it because I am eager to improve my skills with it. During development, ...

Encountering a glitch when attempting to run Bootstrap 4 on an Angular 6 Application

After installing Bootstrap 4 using Angular CLI, I encountered an error when running the application. To resolve this issue, I made changes to the angular.json file: "styles": [ "src/styles.css", "../node_modules/bootstrap/dist/css/bo ...