Show and hide a mat progress bar on app component from child components

Viewed 68

I am new to Angular and is having a small doubt as below

I have a Material Progress bar in My App component

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

and my App Component look like below

export class AppComponent {

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

Now I have 100+ child components where I would like to show progress bar when I make any Api call or long processes

 export class BranchListComponent implements OnInit {  
    
      dataSource = new MatTableDataSource<Branch>(this.Items)
      ngOnInit(): void {    
        this.GetItems();
      }
    
      GetItems() {
    //Here i want to Set     
    AppComponent.IsLoading=true;

        this.branchService.getBranch().subscribe({
          next: (res) => {
            this.response = res;
            if (this.response.isSucess == true) {
        
              this.dataSource = new MatTableDataSource(this.response.value as Branch[]);
        
//Here i want to Set      
          AppComponent.IsLoading=false;
           }
            else {
              alert(this.response.error);
            }
    
          },
          error: (res) => {
            alert("Error while Adding")
          }
        })
      }

Which would be the best and clean way to set the isloading flag from any child components without injecting appcomponent to every child component as viewchild

1 Answers

I recommend you implement a service for this purpose, something like loading.service.ts.

Inject that service wherever you want to toggle "isLoading" and subscribe to the "isLoading" property of the service in the "app-component". When its value gets changed you can reflect it to the "mat-progress-bar" component.

Related