Categories
Angular Tutorials

Build an Angular HTML Table Using httpResource

In this guide we will build a table using live API data.We will use angular httpResource. Which was introduced to simplify asynchronous data handling using signals. Angular Version 22 marks the httpResource API as stable, making it default choice for simple GET requests.

What we are building with angular httpResource

The section shows the final version of our HTML table. The table fetches data from live API (that’s we will cover later) and displays it using angular httpResource.

Simple table of html shows comments using jsonplaceholder api to support angular http resource article on technbuzz.com blog

Project Setup (minimal)

We need a very basic setup, a new project with default setting will be enough.

ng new --minimal --ssr false --style css --ai-config none

We use the minimal setup as testing and extra tooling are outside the scope of this guide

The flags of @angular/cli might change base on the version

This prompt will ask for project name (I think we could provide project name as a flag to above click command)

After that, we will have an Angular project with barebones.

Data Source (JSONPlaceholder)

To start with we need some data to display in the table. I will use the JSONPlaceholder a free public API but you can choose any set of data at your convenience. It has comments endpoint which returns the data in following shape

{
  "postId": 1,
  "id": 1,
  "name": "id labore ex et quam laborum",
  "email": "[email protected]",
  "body": "laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis et nam sapiente accusantium"
}

So by looking at schema we can have following columns (after dropping ID column)

Post IDNameEmailBody
1……

Fetch Data Using Angular httpResource

It’s a wrapper around the same HTTPClient, but returns the signal rather than RxJS observable streams. Those signals can then be combined with other signal friends like computed, linkedSignals etc

comments = httpResource(() => 'https://jsonplaceholder.typicode.com/comments')

#comments = effect(() => {
   console.log(this.comment.value())
})

This is the simplest usage of angular httpResource. We can use value() to get the final result on Line 4. But this will return many hundred comments we need only few of them. We can use params.

For this httpResource provides another overload.

comments = httpResource(() => ({
  url: 'https://jsonplaceholder.typicode.com/comments',
  params: {
    _limit: 10
  }
})

JSONplaceholder accepts _limit params to return a slice of data.

Let’s give it some type safety. By default the value() signal returns undefined. We need to give it some default values such that the template (coming up next) doesn’t complain

//....

type Comment = {
  postId: number;
  id: number;
  name: string;
  email: string;
  body: string;
}

//..
export class Component {
  comments = httpResource<Comment[]>(() => ({
      url: 'https://jsonplaceholder.typicode.com/comments',
      params: {
        _limit: 10
      }
    }), {defaultValue: []},
  );
}

We typed our angular httpResource call with Comment and default value is empty array.

Display Data in an HTML Table

 <table>
   <thead>
     <th>Post ID</th>
     <th>Name</th>
     <th>Email</th>
     <th>Body</th>
  </thead>
  <tbody>
      
  </tbody>
 </table>

The template is narrowed down to table. We do have wrapper elements and some styles. They aren’t discussing here as they are out of the scope of this guide.

 @for(item of comments.value(); track $index) {
   <tr>
     <td>{{ item.id }}</td>
     <td>{{ item.name | slice: 0: 20 }}</td>
     <td class="normal">{{ item.email }}</td>
     <td>{{ item.body | slice: 0: 50 }}</td>
   </tr>
 }

We are just looping over the comment httpResource value signal. The single is consumed just like any other

We have also used the slice pipe to trim the text otherwise it breaks the layout to many lines (by messing with table layout algorithm)

Handle Loading and Error States

We have some helper signals namely isLoading and error with angular httpRequest. Let’s update our HTML accordingly and see it in action

@if(comments.isLoading()) {
  <tr>
    <td colspan="4">Loading...</td>
  </tr>
}
@if(comments.error()) {
  <tr>
    <td colspan="4">Something went wrong</td>
  </tr>
}
@for(item of comments.value(); track $index) {
//.....

Final Result

We are using browser tools to throttle the network to simulate loading and error state

Next Steps (Coming Soon)

We will add some more interacting to this table by adding the sort feature. We will see how the signal interactivity makes it easier to achieve it.

Resources & Repo Links

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.