Home > database >  Angular: How to render only part of the component and not the entire component?
Angular: How to render only part of the component and not the entire component?

Time:12-29

I created a component in Angular. In the component, data comes from a REST API and a database. Now I want only the data from the database to be reloaded because the data from the rest API is taking too long and doesn't necessarily need to be refreshed.

I would not like to implement two different components, otherwise I would have duplicate code and it would violate against DRY (don't repeat yourself).

My question: Is it somehow possible to re-render or load only a part of the component and not the whole component?

blueprint

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <div >
      <div>
        <div>Data from rest API</div>
      </div>

      <div>
        <div>Data from DB</div>
        <div>Data from DB</div>
      </div>
    </div>
  `
})

export class AppComponent {}

CodePudding user response:

To me this sounds like you are taking the wrong approach here. I think there shouldn't be one such big component, but multiple components for your cause. You even named the one component <div > Meaning it is a wrapper for components.

I think you can create one component that handles rendering the data.

<div >
      <div *ngFor="let dataFromAPI = dataListFromAPI">
        <app-data-rendering [data]="dataFromAPI"> </app-data-rendering>
      </div>

      <div *ngFor="let dataFromDB = dataListFromDB">
         <app-data-rendering [data]="dataFromDB"></app-data-rendering>
      </div>
    </div>

Note The dataListFromAPI and dataListFromDB are two arrays, each holding the respective response from the data calls. If you do a new call for updating the dataListFromAPI only components with the updated dataListFromAPI variable will be rerenderd.

CodePudding user response:

You can use rxjs methods to achieve it.
In component you can create variables:

dataFromApi$!: Observable<type>;
dataFromDb$!: Observable<type>;

ngOnInit() {
    this.dataFromApi$ = yourApiService.yourGetMethod()
    //same for database
}

in template you subscribe to it and display only when data has arrived

  <div *ngIf="dataFromApi$ | async">
    <div>Data from rest API</div>
  </div>
  • Related