Sunday, January 14, 2024

Angular Example to Render Multiple Rows

In this Angular example we’ll see how to render multiple rows. There will be a UI for entering data and a submit button. After entering data when user clicks submit button the entered data is displayed below it. User can again enter the data and a new row will be displayed below the previously displayed data. This Angular example shows the usage of property binding, event binding, @Input decorator and ngFor directive.

Here is a screen shot which shows the final UI created using this Angular example for rendering multiple rows.

Angular example rendering rows


Angular example steps

  1. In your Angular project create a new folder User for keeping classes created for this example.
  2. Create a User class, it is a best practice to create a separate model bean class rather than keeping data in the Component class to reduce coupling.
  3. Create a new User component class that uses the User class to render data. In the example when data is entered using UI a new User class instance is created and data of the instance is rendered using User component. So every time data is entered and submit button is clicked a new User class instance is created and rendered as a new row.
  4. For storing multiple User instances an array of type User (User[]) is used.

Creating a User class

Create a Type script class user.model.ts to define a User class. If you are aware of MVC (Model View Controller) pattern then this class is the Model.

export class User {
  name : string;
  age : number;
  constructor(name: string, age : number) {
    this.name = name;
    this.age = age;
  }
}

Creating User component class

Create a Type script class user.component.ts

import { 
  Component,
  OnInit,
  Input
 } from '@angular/core';
import { User } from './user.model';
@Component({
  selector: 'app-user',
  templateUrl: './user.component.html'
})
export class UserComponent implements OnInit{
  @Input() user: User;
  constructor(){
  
  }
  ngOnInit(){
  }
}
  1. As you can see Component class uses User class to store instance data thus the import statement.
     import { User } from './user.model';
     
  2. @Input decorator marks a class field as an input property. The input property is bound to a DOM property in the template. During change detection, Angular automatically updates the data property with the DOM property's value. In our component we want to pass data to the user property thus it is decorated with @Input decorator. Because of using @Input with user property Angular uses user as an input binding.
    We’ll see a little later how property binding is done to bind a custom property to user instances. This custom property is then passed to the User component to display user data using input binding.

Creating template for displaying user data

Create user.component.html which is used to render user data. Bootstrap framework is used for styling.

<div class="container">
  <div class="row">
    <div class="col-xs-6 px-3">
      <label>Name: </label> {{ user.name }}      
    </div>
    <div class="col-xs-4">
      <label>Age: </label>{{ user.age }}
    </div>
  </div>
</div>

Changes in app module to register user component

If you have not created new component using Angular CLI then you need to manually import the component in app.module.ts file.

import { UserComponent } from './user/user.component';

Also add with in the declarations array in @NgModule decorator.

@NgModule({
  declarations: [
    AppComponent,
    UserComponent
    //HelloWorldComponent
  ],
..
..

Template for adding users

Add the following code in app.component.html

<form>
  <div class="form-group">
    <label for="name" class="col-sm-2 col-form-label">Name:</label>
    <div class="col-sm-10">
      <input class="form-control" placeholder="Enter name" id="name" #enteredname>
    </div>
  </div>
  <div class="form-group">
    <label for="age" class="col-sm-2 col-form-label">Age:</label>
    <div class="col-sm-10">
      <input class="form-control" placeholder="Enter age" id="age" #enteredage>
    </div>
  </div>
  <button (click)="addUser(enteredname, enteredage)" type="submit" class="btn btn-primary">Submit</button>
</form>

<app-user *ngFor="let user of users" [user]="user">
</app-user>

This template renders a form for adding users.

  1. In the template there are two input tags- one for entering user name and the other for age.
  2. #enteredname and #enteredage are local variables used with the tags. The input tags are assigned to these local variables.
  3. There is a submit button where we have also added an event (click) which calls the function addUser when the button is clicked. Note that function addUser is defined in AppComponent class.
  4. addUser() function takes two arguments. While calling the function the two variables #enteredname and #enteredage are passed.
  5. ngFor directive is used to iterate through the array of users and assign user instance to variable named user in each iteration.
  6. [user]="user" expression is the property binding. This binding is setting the user input (@Input() user: User in the user.component.ts) to the value of the variable user assigned here by ngFor.

app.component.ts

import { Component } from '@angular/core';
import { User } from './user/user.model';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  users: User[];
  constructor(){
    this.users = [];
  }
  addUser(name: HTMLInputElement, age: HTMLInputElement): boolean {
    //console.log(`user name: ${name.value}, age: ${age.value}`);
    // adding user instance to array
    this.users.push(new User(name.value, Number(age.value)));
    // resetting input elements
    name.value = '';
    age.value = '';
    return false;
  }
}

1. In the Component class User class is imported using this statement- import { User } from './user/user.model';

2. users: User[]; declares an array users of type User.

3. adduser() function which is called when the submit button is clicked is defined here. In the function, using the entered values a new User instance is created and added to the users array.

Build the code and access the URL http://localhost:4200/ which should render the screen to enter User data.

That's all for this topic Angular Example to Render Multiple Rows. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Angular Disable Button Example
  2. Angular First App - Hello world Example
  3. Angular Project Structure With File Description
  4. How to Add Bootstrap to Angular Application
  5. Creating New Component in Angular

You may also like-

  1. Angular @Input and @Output Example
  2. Angular One-Way Data Binding Using String Interpolation
  3. Angular Application Bootstrap Process
  4. Angular - Call One Service From Another
  5. CallableStatement Interface in Java-JDBC
  6. Producer-Consumer Java Program Using wait notify
  7. Concatenating Lists in Python
  8. Java Collections Interview Questions And Answers