Toggle the visibility of a material progress bar on the app component using child components

I'm currently learning Angular and have a small question about it.

In my App component, I have a Material Progress bar like this:

<mat-progress-bar mode="indeterminate" *ngIf="IsLoading"></mat-progress-bar>
<router-outlet></router-outlet>

and here is how my App Component looks:

export class AppComponent {

  IsLoading: boolean=true;
  title = 'CBEAAPPMAIN';
}

Now, I have over 100 child components where I need to display the progress bar when making API calls or during long processes.

 export class BranchListComponent implements OnInit {  
    
      dataSource = new MatTableDataSource<Branch>(this.Items)
      ngOnInit(): void {    
        this.GetItems();
      }
    
      GetItems() {
    //I need help with setting 
    AppComponent.IsLoading=true;

        this.branchService.getBranch().subscribe({
          next: (res) => {
            this.response = res;
            if (this.response.isSuccess == true) {
        
              this.dataSource = new MatTableDataSource(this.response.value as Branch[]);
        
//I also need help with setting      
          AppComponent.IsLoading=false;
           }
            else {
              alert(this.response.error);
            }
    
          },
          error: (res) => {
            alert("Error while Adding")
          }
        })
      }

What would be the most efficient and clean way to set the isLoading flag from any child component without injecting appComponent to every child component as ViewChild?

Answer №1

To streamline your process, I suggest creating a dedicated service such as loading.service.ts.

Once you have the service set up, inject it into any components where you need to manage the "isLoading" status and subscribe to the changes in the "isLoading" property within the "app-component". This way, you can easily update the state of the "mat-progress-bar" component based on the value of "isLoading".

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

Type of tuple without a specific order

Exploring Typescript typings has led me to ponder how to create a type that is a tuple with unordered element types. For example: type SimpleTuple = [number, string]; const tup1: SimpleTuple = [7, `7`]; // Valid const tup2: SimpleTuple = [`7`, 7]; // &ap ...

Give the Row ID as a parameter to a personalized component within MUI Datagrid Pro

I am currently exploring the idea of incorporating an intermediate state to row checkboxes based on the selection status of other checkboxes within a detailed panel. My approach involves crafting a custom checkbox component and implementing some logical ...

Typescript tutorial: Implementing a 'lambda function call' for external method

The Issue Just recently diving into Typescript, I discovered that lambda functions are utilized to adjust the value of this. However, I find myself stuck on how to pass my view model's this into a function that calls another method that hasn't b ...

What is the process for combining two services into a single, unified service?

In my Angular 8 application, I have a service structured like this: export class ProfileUserService { user$ = this.authService.loginStatus().pipe(take(1)); constructor(private profileService: ProfileService, private authService: AuthService) {} ge ...

Issue encountered after updating to Spartacus 3.0 from 2.0: Unable to access the 'findStores' property due to a TypeError

After upgrading to Spartacus 3.0 from 2.0, everything seems to be working fine except for this particular error that keeps popping up. I followed the steps provided by SAP team on the documentation site to add the storefinder module. https://i.sstatic.net ...

What is the process for importing a package in AtmosphereJS?

Despite following the steps outlined in this guide for using atmosphere packages in my meteor project, I am encountering errors when I run meteor. One specific issue I am facing is with the vsivsi:job-collection package. When I try to reference it like th ...

Unable to find the required dependency: peer tslint@ "^5.0.0 || ^6.0.0" in [email protected] node_modules/codelyzer development codelyzer@ "^5.1.2" from the main project directory

Struggling to create my angular project, I've attempted updating @angular/core and even deleted the node modules folder and reinstalled it. I also played around with the version of my node and npm, but nothing seems to work. Here's the error: [1 ...

What is the significance of TypeScript's dual generic typing feature?

defineListenerShape< EventName extends string, EventData extends { [key in EventName]: unknown; } > = <E extends EventName>(data: EventData[E]) => void; enum EventName { Click = 'click', Hover = 'hover' ...

Conditional statements in Typescript can be utilized when dealing with unknown data types

In one of my projects, I have a function that executes an asynchronous operation over a collection. I want to add typings to this function for better IDE support - specifically, I want the IDE to infer that the first parameter in the callback function is o ...

When sending a JSON string in an HTTP request with Express, the req.body variable may be empty

I'm facing an issue where Express is receiving an empty JSON string {} and I've been struggling to identify the cause. I've attempted using both bodyParser and express.json for the JSON parser, but the result remains the same. I've also ...

Only permitting elements of type U based on the value of T - advanced generic restrictions

Seeking assistance with adding constraints to generics in a signature. The current setup is functioning well. Interested in implementing constraints based on the types of another type. async publish<T>(exchange: Exchange, routingKey: RoutingKey, m ...

Incorporating new element into a Typescript array

I'm currently working on a project using TypeScript and MongoDB where I need to insert an item into an array. registeredUsers.update({ guid: ObjectId(req.cookies._id) }, { $addToSet: { favorites: [comicID] } }); The code snippet prov ...

The TS2339 error has occurred because the "email" property cannot be found on the specified "Object" type

I encountered an issue while using Angular 5, here is the code snippet : signIn(provider) { this._auth.login(provider).subscribe( (data) => { console.log(data); this.hideForm = false; this.emaill = data.email; ...

Obtain the text that is shown for an input field

My website is currently utilizing Angular Material, which is causing the text format in my type='time' input field to change. I am looking for a way to verify this text, but none of the methods I have tried give me the actual displayed text. I a ...

Simplified File Paths and Default Files

Currently, I am working with Next.js and TypeScript, setting up path aliases in my project without any issues. However, I'm facing a small difficulty when it comes to dealing with index.ts files within folders. My goal is to achieve something similar ...

Problem arises when combining string manipulation and piping operations

I have an HTML code within an Angular 2.0 template that looks like this: <span> Total Employee {{employeeCount> 0 ? '(' + employeeCount+ ')' : ''}} ></span> My customFormatter function is able to take a val ...

Is it achievable to dynamically modify the style URL in an Angular component based on certain conditions?

element: I am working with two different CSS files, one for Arabic layout and one for English layout. I am wondering if it is possible to conditionally change the style URL in the component. Is this feasible? ...

Customizing event typings for OpenTok in Typescript

Currently, I am working on integrating chat functionality using the 'signal' events with the OpenTok API. Here is my event listener that successfully receives the signal: // Listen for signal CHAT_MESSAGE sess.on('signal:CHAT_MESSAGE', ...

Executing a Prisma query with a selection

My Prisma models involve User, Car, and Reservation entities: model User { id String @id @default(auto()) @map("_id") @db.ObjectId name String? email String? @unique emailVerified DateTime? image ...

Tips for infuriating TSC with Lookup categories

I'm looking for the Typescript compiler (TSC) to throw errors when I make mistakes in signatures. export class EventEmitter<EventTypes extends { [key: string]: any }> { subscribe<Event extends keyof EventTypes>(type: keyof EventTypes, ...