Friday, April 3, 2020

Angular ngSwitch Directive With Examples

In the post Angular ngIf Directive With Examples we saw how to use ngIf directive but you may have a scenario where you need to render different elements based on different conditions. In such scenario you can use Angular ngSwitch directive rather than using ngIf several times.

Angular ngSwitch directive

The [ngSwitch] directive on a container specifies an expression to match against. The expressions to match are provided by ngSwitchCase directives on views within the container.

Syntax of Angular ngIf

<container-element [ngSwitch]="switch_expression">
   <some-element *ngSwitchCase="match_expression_1">...</some-element>
   <some-element *ngSwitchCase="match_expression_2">...</some-element>
   ...
   <some-element *ngSwitchDefault>...</some-element>
</container-element>
  1. Every view that matches is rendered.
  2. If there are no matches, a view with the ngSwitchDefault directive is rendered.
  3. ngSwitchDefault element is optional. If you don't use it, nothing will be rendered when there is no matching value.
  4. Note that asterisk (*) precedes the ngSwitchCase which means it is a structural directive and used to add or remove DOM element.
  5. If the value of the match_expression matches the value of the switch_expression, the corresponding element is added to the DOM. If the expression doesn’t match, then the element is excluded from the DOM.
  6. The element that the ngSwitch directive is applied to is always included in the HTML document, ngSwitch is specified within square brackets.

Angular ngSwitch directive examples

There is an array of numbers and using ngSwitch you check if array length is equal to the passed number in ngSwitchCase or not.

Component

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  numArray: number[];
  size : number;

  constructor(){
    this.numArray = [1,2,3];
  }

  getSize() : number{
    this.size = this.numArray.length;
    return this.numArray.length;
  }
}

Template

<div class="container">
    <div class="row">
        <div class="col-xs-12">
            <div>There are {{ getSize() }} numbers.</div>
            <div [ngSwitch]="getSize()">
                <span *ngSwitchCase="0">No number is added</span>
                <span *ngSwitchCase="1">One number is added</span>
                <span *ngSwitchCase="2">Two numbers are added</span>
                <span *ngSwitchCase="3">Three numbers are added</span>
            </div>
        </div>
    </div>
</div>

As you can see ngSwitchDefault is omitted here. If you want to add it then-

<div [ngSwitch]="getSize()">
    <span *ngSwitchCase="0">No number is added</span>
    <span *ngSwitchCase="1">One number is added</span>
    <span *ngSwitchCase="2">Two numbers are added</span>
    <span *ngSwitchCase="3">Three numbers are added</span>
    <span *ngSwitchDefault>More than three numbers are added</span>
</div>

ngSwitch with String values

If you are matching a literal string then you have to enclose it in single quotes. Suppose there is an array of Strings and you pass one of the character from that array.

In the ngSwitch you want to match that character.

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  strArray: String[];
  constructor(){
    this.strArray = ['A', 'B', 'C', 'D'];
  }

  getChar() : String{
    return this.strArray[0];
  }
}

Template

<div class="container">
    <div class="row">
        <div class="col-xs-12">
            <div [ngSwitch]="getChar()">
                <span *ngSwitchCase="'A'">Got A from the array</span>
                <span *ngSwitchCase="'B'">Got B from the array</span>
                <span *ngSwitchCase="'C'">Got C from the array</span>
                <span *ngSwitchCase="'D'">Got D from the array</span>
                <span *ngSwitchDefault>Soem other alphabet</span>
            </div>
        </div>
    </div>
</div>

As you can see string are enclosed in single quotes for matching the literal Strings.

That's all for this topic Angular ngSwitch Directive With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Angular Project Structure With File Description
  2. Angular Application Bootstrap Process
  3. Angular First App - Hello world Example
  4. Angular @Component Decorator

You may also like-

  1. Angular Example to Render Multiple Rows
  2. Angular @Input and @Output Example
  3. Core Java Basics Interview Questions And Answers
  4. ConcurrentHashMap in Java
  5. New Date And Time API in Java 8
  6. StringJoiner Class in Java With Examples
  7. Magic Methods in Python With Examples
  8. Dependency Injection in Spring Framework

Wednesday, April 1, 2020

Angular ngIf Directive With Examples

Angular provides some of the built-in directives to perform the most common tasks in web application development. Angular ngIf directive is used to conditionally include or remove an element in the HTML document.

If the expression used with the ngIf directive evaluates to true, element is included in the DOM if expression evaluates to false then the element is removed from the DOM.

Here are some examples of ngIf directive-

1. <div *ngIf="true"></div>

Element is always displayed.

2. <div *ngIf="false"></div>

Element is never displayed.

3. <div *ngIf="x > y"></div>

Element is displayed if x is greater than y.

4. <div *ngIf="myFunc()"></div>

Element is displayed if myFunc returns true.


ngIf is a structural directive

As you would have seen in the above examples, asterisk (*) precedes the ngIf directive attribute which means it is a structural directive.

Structural directives are responsible for HTML layout. They change the DOM's structure, typically by adding, removing, or manipulating elements.

Internally Angular translates the *ngIf attribute into a <ng-template> element. If you have a statement as given below

<div *ngIf="user" class="name">{{user.name}}</div>

It is translated into a <ng-template> element, wrapped around the host element, like this.

<ng-template [ngIf]="user">
  <div class="name">{{user.name}}</div>
</ng-template>

Angular ngIf example to display element

In the component there is a boolean flag and the element is displayed in the template based on whether the boolean flag is true or false.

app.component.ts

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  toggle : boolean = true;
}

app.component.html

<div class="container">
    <div class="row">
        <div class="col-xs-12">
            <p *ngIf="toggle">This text is displayed conditionally using ngIf</p>
        </div>
    </div>
</div>

If you see in the above example value of the toggle boolean variable is not changed once it is assigned. You can add a button to toggle the display.

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  toggle : boolean = true;
  
  onClickToggle(){
    this.toggle = !this.toggle;
  }
}

Now there is a onClickToggle() function where the value of the toggle variable is reversed.

<div class="container">
    <div class="row">
        <div class="col-xs-12">
            <button class="btn btn-primary" 
                (click)="onClickToggle()">
                Display
            </button>
            <p *ngIf="toggle">This text is displayed conditionally using ngIf</p> 
        </div>
    </div>
</div>

Now the paragraph is removed when the button is clicked and it appears again when the button is clicked again.

Comparison (===) using ngIf

You can also use ngIf for comparing variables, if comparison returns true element is displayed otherwise it is not displayed.

In the component there is a string variable and the element is displayed in the template based on whether the string variable has the certain value or not.

app.component.ts

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  show : String;
  constructor(){
    this.show = "yes";
  }
}

app.component.html

<div class="container">
    <div class="row">
        <div class="col-xs-12">
            <p *ngIf="show === 'yes'">This text is displayed conditionally using ngIf</p>
        </div>
    </div>
</div>

Angular ngIf to check if object exists

You can also use ngIf to check if object exists before trying to access its fields.

For example you are trying to display name property of the user when no User instance is initialized.

<p><label>Name: </label> {{user.name}} </p>

If you want to display the element only if user instance exists then you can use ngIf to do a check.

<p ngIf="user"><label>Name: </label> {{user.name}} </p>

Here is the complete example.

User Model class

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

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 {
  user : User;
  constructor(){
    // creating user instance
    this.user = new User('Jack', 56, new Date('2005-03-25'));
  }
}

In the component class User class is imported and in the constructor a new instance is also created.

app.component.html

<div class="container">
    <div class="row">
        <div class="col-xs-12">
            <p *ngIf="user"><label>Name: </label> {{user.name}} </p>      
        </div>
    </div>
</div>

The ngIf directive doesn't hide elements with CSS. It adds and removes them physically from the DOM. You can confirm it by inspecting the DOM.

Angular ngIf Directive

Now you can comment the user instance in the constructor.

ngIf Directive example

As you can see now the whole element is removed from the DOM.

ngIf with else

You can also have an else block with if making it if-else conditional statement where if block is executed when the conditional expression resolves to true and else block is executed if expression is false.

Here is an example of the template with ngIf–else

<div class="container">
    <div class="row">
        <div class="col-xs-12">
            <div *ngIf="show; else elseBlock">This text is displayed when condition is true</div>
            <ng-template #elseBlock>This text is displayed when condition is false.</ng-template>
        </div>
    </div>
</div>

As you can see a local reference #elseBlock is placed with <ng-template> which is used to mark a location in DOM.

app.component.ts

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  show : boolean;

  constructor(){
    this.show = true;
  }
}

ngIf with then and else

Though not used that commonly but you can also have both then and else block with ngIf. Then part is executed if the condition is true, else block is executed otherwise.

<div *ngIf="show; then thenBlock else elseBlock"></div>
<ng-template #thenBlock>This text is displayed when condition is true.</ng-template>
<ng-template #elseBlock>This text is displayed when condition is false.</ng-template>

That's all for this topic Angular ngIf Directive With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Angular ngSwitch Directive With Examples
  2. Angular Project Structure With File Description
  3. Angular Application Bootstrap Process
  4. Angular First App - Hello world Example
  5. Angular @Component Decorator

You may also like-

  1. Angular Example to Render Multiple Rows
  2. Angular @Input and @Output Example
  3. Core Java Basics Interview Questions And Answers
  4. ConcurrentHashMap in Java
  5. New Date And Time API in Java 8
  6. StringJoiner Class in Java With Examples
  7. Magic Methods in Python With Examples
  8. Dependency Injection in Spring Framework

Tuesday, March 31, 2020

Angular @Component Decorator

Decorators or annotations are used to provide metadata about the entity where these decorators are added. Angular @Component decorator provides metadata about the class and tells Angular that the decorated class is a Component class.

Angular @Component provides configuration metadata that determines how the component should be processed, instantiated, and used at runtime.

For example-

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
 ...
 ...

As you can see selector property here specifies value as ‘app-root’ which means any <app-root></app-root> tags that are used within a template will be compiled using the AppComponent class and get the functionality as defined in the class.

templateUrl is specified as ./app.component.html which means view template is loaded from the file app.component.html in the current directory.

Using styleUrls you can specify One or more relative paths or absolute URLs for files containing CSS stylesheets to use in this component. Here ./app.component.css is specified as css file which means styling for the component is done using hello-world.component.css in the current directory. By specifying style fields like this you can associate a specific css file to a component.

Apart from these three options there are many more options you can specify with @Component decorator.

1. changeDetection- Using this option you can specify the change-detection strategy to use for this component. When a component is instantiated, Angular creates a change detector, which is responsible for propagating the component's bindings.

There are two options-

  • OnPush- sets the strategy to CheckOnce (on demand).
  • Default- sets the strategy to CheckAlways.

To use it you need to import ChangeDetectionStrategy from '@angular/core' and then specify the startegy as

changeDetection: ChangeDetectionStrategy.OnPush

2. template- Rather than specifying a separate template file using templateURL you can provide inline template for an Angular component using template option.

3. styles- Just like template using styles you can provide one or more inline CSS stylesheets using styles option.

Here is an example of Angular component where inline CSS is provided using styles option and inline template is provided using template option.

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

@Component({
  selector: 'app-hello-world',
  styles: [`
    .highlight {
      background-color: yellow;
      font-family: Helvetica, Arial;
      font-size: 16px;
    }
  `],
  template: `
    <h4 class="ui horizontal divider header">
      This is inline Template example
    </h4>
    <span class="highlight">Hello Users</span>
  `
})
export class HelloWorldComponent {
  constructor() { }

}
@Component Decorator in Angular

That's all for this topic Angular @Component Decorator. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to Install Node.js and NPM in Windows
  2. How to Setup Angular
  3. Angular Application Bootstrap Process
  4. Angular Project Structure With File Description
  5. Creating New Component in Angular

You may also like-

  1. Angular First App - Hello world Example
  2. Angular Example to Render Multiple Rows
  3. Difference Between equals() Method And equality Operator == in Java
  4. MapReduce Flow in YARN
  5. Java Program to Detect And Remove Loop in a Linked List
  6. Spring MVC - Binding List of Objects Example

Friday, March 27, 2020

Angular @Input and @Output Example

In the post Angular Example to Render Multiple Rows we saw an example demonstrating the use of @Input decorator in Angular and property binding. In this post we’ll see an example showing the use of both @Input and @Output decorator in Angular.

@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.

@Output decorator with EvenEmitter is used to emit an event from the component. You’ll have more clarity as we progress through the example.

Steps in Angular @Input and @Output example

The requirement is to show a list of user names. When a user name is clicked details of that particular users are displayed.

Screens for the example would be something like this-

First user names are displayed

Angular @Input and @Output decorator

Display user details for the selected User

Angular @Output with EvenEmitter

What is needed

  1. You need a model class for User fields.
  2. There will be one component for showing user names and another component for showing User details. So there will be two child component of app.component and the interaction from parent to child and vice versa will happen using @Input and @Output decorators.

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. There are 3 fields name, age and joinDate in the User class.

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

Creating user.component class

Create a Type script class user.component.ts with properties decorated with @Input and @Output decorators.

import { 
    Component,
    EventEmitter,
    Input, 
    Output
 } from '@angular/core';
import { User } from './user.model';
@Component({
  selector: 'app-user',
  templateUrl: './user.component.html'
})
export class UserComponent{
    @Input() user: User;
    @Output() onUserSelected: EventEmitter<User>;
    constructor(){
        this.onUserSelected = new EventEmitter();
    }
    
    userClicked() : void{
      this.onUserSelected.emit(this.user);
    }
}

In this component we want to get data in the user property thus it is decorated with @Input decorator. Because of using @Input decorator with user property Angular uses user as an input binding. So you can say that we’ll pass User instance from parent component app.component.ts to the child component user.component.ts and field marked with @Input decorator gets that user instance.

OnUserSelected property in user.component.ts is decorated with @Output decorator and of type EventEmitter<User> that means it will emit User instance (using emit function) which should be received by the parent component.

Creating user.component.html template

<div class="container">
    <div class="row">
        <div class="col-xs-6">
            <label>Name: </label><span (click)='userClicked()'> {{ user.name }}</span>
        </div>
    </div>
</div>

This template displays user names and you can see there is also an event binding for click event calling the userClicked() function in the .ts class when any user name is selected. In the user.component.ts class we have already seen with in the userClicked() function that particular user instance is emitted.

app.component.ts class

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 {
  //username : String;
  users: User[];
  currentUser : User;
  constructor(){
    // Adding user instances in the users array
    this.users = [new User('Jack', 56, new Date('2005-03-25')),
                  new User('Lisa', 32, new Date('2012-05-09')),
                  new User('Jayesh', 28, new Date('2014-10-21'))] ;
  }

  showUser(user: User) : void {
    // Setting selected user to currentUser
    this.currentUser = user;
    //console.log('User: ', user );
  }

  // Function used to determine the selected user
  // so that its color can be changed 
  isSelected(user: User): boolean {
    if (!user || !this.currentUser) {
      return false;
    }
    return user.name === this.currentUser.name;
  }
}

In the class there is an array of type User, in the constructor user instances are created and stored in this array.

There is also a showUser(user: User) function, this is the method which stores the emitted user instance (from child component user.component).

isSelected() function determines which user name is selected, this helps in styling the selected user name.

app.component.html template

<div class="container">
    <h3>Click user name to see user details</h3>
    <app-user *ngFor="let user of users" 
            [user]="user"
            (onUserSelected)="showUser($event)"
            [class.alert-primary] = "isSelected(user)">
    </app-user>
</div>

<div class="container">
    <user-data *ngIf="currentUser" [user]="currentUser">
    </user-data>
</div>

ngFor iterates over the User array and each user instance is assigned to a user variable [user]="user", this expression also passes the value stored in user variable to the user property decorated with @Input decorator in user.component.ts class. Just keep in mind that the square brackets are used for input binding.

(onUserSelected)="showUser($event)" is for handling output. You have configured (onUserSelected) output to listen to the event and call function showUser() when data is emitted.

[class.alert-primary] = "isSelected(user)" is used to set css class conditionally based on the bollean values returned by the associated function. If isSelected() function returns true then the alert-primary (from Bootstrap) css class is added.

There is another div section in the template.

<div class="container">
    <user-data *ngIf="currentUser" [user]="currentUser">
    </user-data>
</div>

This is used for displaying user details. Using ngIf it is checked if currentUser has any value or not. If there is any assigned value then only it is assigned to the local variable user which also is an input binding for user property in userdata.component.

userdata.component.ts class

import { 
    Component,
    Input
 } from '@angular/core';
import { User } from './user.model';
@Component({
  selector: 'user-data',
  templateUrl: './userdata.component.html'
})
export class UserDataComponent{
    @Input() user: User;
    constructor(){
    }
}

As you can see in this type script class too there is a user property which is decorated using @Input decorator. This user property gets user data from the second div section of the app.component.html shown above.

userdata.component.html template

<div class="jumbotron">
    <div class="container">
        <h2>User Details</h2>
        <div class="row">
            <div class="col-xs-5 px-3">
                <label>Name: </label> {{ user.name }}      
            </div>
            <div class="col-xs-4 px-3">
                <label>Age: </label> {{ user.age }}
            </div>
            <div class="col-xs-4 px-3">
                <label>Joining Date: </label> {{ user.joinDate | date:'dd/MM/yyyy'}}
            </div>
        </div>
    </div>
</div>

This template shows user details for the selected user. Note that, for date, DatePipe is used to format the date.

Changes in app module to register created components

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

Add import statements.

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

Add to declarations array within @NgModule decorator.

@NgModule({
  declarations: [
    AppComponent,
    UserComponent,
    UserDataComponent
  ],
  imports: [
 ..
 ..

That's all for this topic Angular @Input and @Output Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Angular Project Structure With File Description
  2. Angular Application Bootstrap Process
  3. Creating New Component in Angular

You may also like-

  1. Angular First App - Hello world Example
  2. Java String Interview Questions And Answers
  3. Can we Start The Same Thread Twice in Java
  4. throws Keyword in Java Exception Handling
  5. BigDecimal in Java
  6. Sending Email Using Spring Framework Example
  7. Tuple in Python With Examples

Tuesday, March 24, 2020

Angular Example to Render Multiple Rows

In this Angular example we’ll see how to render multiple rows. So 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!


Related Topics

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

You may also like-

  1. Volatile Keyword in Java With Examples
  2. Try-With-Resources in Java With Examples
  3. CallableStatement Interface in Java-JDBC
  4. Producer-Consumer Java Program Using wait notify
  5. Concatenating Lists in Python
  6. Java Collections Interview Questions And Answers

Tuesday, March 17, 2020

Creating New Component in Angular

Components are the building block of any Angular application. A well designed UI should break its rendering into different components where each component renders the particular portion of the UI. That makes it more manageable and also the same components can be reused. In this article we’ll see how you can create a component in Angular.

Creating component in Angular

You can create a component using one of the following ways-

  • Using Angular CLI
  • Creating component manually

Creating component using Angular CLI

Navigate to the root folder of your Angular application and run the following command to create a new component.

ng generate component COMPONENT_NAME

OR

ng g c COMPONENT_NAME

If I want to create a component named hello-world then it can be done as given below-

F:\NETJS\Angular WS\hello-world-app>ng generate component hello-world

CREATE src/app/hello-world/hello-world.component.html (26 bytes)
CREATE src/app/hello-world/hello-world.component.spec.ts (657 bytes)
CREATE src/app/hello-world/hello-world.component.ts (294 bytes)
CREATE src/app/hello-world/hello-world.component.css (0 bytes)
UPDATE src/app/app.module.ts (576 bytes)

As you can see creation of component results in creation of 4 new files and also in automatic updation of app.module.ts. Created files have specific roles as given here-

  1. hello-world.component.ts- This is the class where code for the component is written in TypeScript.
  2. hello-world.component.html- The component template, written in HTML.
  3. hello-world.component.css- The component's private CSS styles.
  4. hello-world.component.spec.ts- Defines a unit test for the hello-world component.

The update in the app.module.ts is-

  • Inclusion of import statement to import the type script file of the newly created component.
  • Inclusion of newly created component in the declarations array with in the @NgModule decorator.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { HelloWorldComponent } from './hello-world/hello-world.component';

@NgModule({
  declarations: [
    AppComponent,
    HelloWorldComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Changing HTML template

Let’s change the template src/app/hello-world/hello-world.component.html and add some code.


<!--Using Bootstrap for styling-->
<div class="container">
    <div class="row">
        <div class="col-xs-12">
            <h1>Success Message</h1>
            <p class="text-succcess"><strong>Success!</strong> Able to create a component.</p>
        </div>
    </div>
</div>

Note that in the html, bootstrap is used. Refer to see how to add Bootstrap to angular.

Also add the <app-hello-world> tag in the app.component.html to render the view.

<app-hello-world></app-hello-world>

Now if you build the application using ng serve command and access the URL http://localhost:4200/ you should see the rendered template.

Creating component in Angular

Creating component manually

You can also create a component manually. Once you have the Angular project structure created using ng new command you can open it in the IDE you are using. I am using Visual Code here but the steps remain same.

Go the src-app folder with in your opened application right click – New Folder and create a new Folder for your component. I have named it “hello-world”.

Angular development using Visual code

Right click the newly created component folder and select new file and create the following two files for Type Script and Template.

  • hello-world.component.ts
  • hello-world.component.html

Open hello-world.component.ts and copy the following code.

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

@Component({
  selector: 'app-hello-world',
  templateUrl: './hello-world.component.html'
})
export class HelloWorldComponent implements OnInit {

  constructor() { }

  ngOnInit(){
  }
}

Open hello-world.component.html and copy the following code.


<!--Using Bootstrap for styling-->
<div class="container">
    <div class="row">
        <div class="col-xs-12">
            <h1>Success Message</h1>
            <p class="text-succcess"><strong>Success!</strong> Able to create a component.</p>
        </div>
    </div>
</div>

In the app.module.ts add the import statement for the new component as well as add it in declarations array too with in @NgModule decorator.

import { HelloWorldComponent } from './hello-world/hello-world.component';

@NgModule({
  declarations: [
    AppComponent,
    HelloWorldComponent
  ],

Also add the <app-hello-world> tag in the app.component.html to render the view. Note that this tag should match the Selector attribute value of @Component decorator used in Component class.

<app-hello-world></app-hello-world>

With this, manually creating component in Angular is done, you can build the application using ng serve command and access the URL http://localhost:4200/

That's all for this topic Creating New Component in Angular. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Angular First App - Hello world Example
  2. How to Install Node.js and NPM in Windows
  3. How to Setup Angular
  4. Angular Project Structure With File Description
  5. Angular Application Bootstrap Process

You may also like-

  1. Python Exception Handling Tutorial
  2. Java Multithreading Interview Questions And Answers
  3. Spring Boot StandAlone (Console Based) Application Example
  4. Spring MVC Exception Handling Example Using @ExceptionHandler And @ControllerAdvice
  5. Bounded Type Parameter in Java Generics
  6. Main Thread in Java
  7. Difference Between Runnable And Callable in Java
  8. How to Loop Through HashSet in Java

Monday, March 16, 2020

How to Add Bootstrap to Angular Application

In this article we’ll see how to add Bootstrap to your Angular application so that you can style your templates. Bootstrap is one of the most popular HTML and CSS framework for building responsive UI and used widely with JS frameworks like Angular to create a better user experience.

Including Bootstrap in Angular application

In order to add Bootstrap to Angular application of course the first step is to have an Angular application.

Installing Bootstrap using NPM

You can install Bootstrap using NPM, first go to the root folder of your Angular application and run the following command.

npm install --save bootstrap jquery

Above command installs the latest version of Bootstrap as well as of jquery. If you want to install specific version of Bootstrap then you can specify the version with the command as given below-

npm install bootstrap@version_num
Verifying the installation

Installation of the Bootstrap and JQuery module is done inside the node_modules directory of your Angular application. You can verify that the folder with the same name i.e. bootstrap and jquery exists in the node_modules directory.

Adding bootstrap to Angular app

Now you need to make Angular aware of the location of the bootstrap and jquery. For that you can add it to the angular.json file.

Open angular.json and add the path to the bootstrap and jquery in the “styles” and “scripts” arrays respectively.

"styles": [
 "node_modules/bootstrap/dist/css/bootstrap.min.css",
              "src/styles.css"
],
"scripts": [
 "node_modules/bootstrap/dist/js/bootstrap.min.js",
 "node_modules/jquery/dist/jquery.min.js"
]

Now if you build your application using ng serve command and access URL http://localhost:4200/ you can check the elements in the Developer tools to see that Bootstrap is included.

Adding Bootstrap to Angular

Another way to add Bootstrap and js files is to add the paths to the src/index.html file using <link> and <script> tags.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>HelloWorldApp</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.min.css">
</head>
<body>
    
  <app-root></app-root>
   <script src="../node_modules/jquery/dist/jquery.min.js"></script>
  <script src="..node_modules/bootstrap/dist/js/bootstrap.min.js"></script>  
</body>
</html>

Doing styling with Bootstrap

Now we can do styling using Bootstrap, here is a simple example with changes in app.component.html file.

<div class="container">
    <div class="row">
    <div class="col-xs-12">
    <h1>{{title}}</h1>
    <p>I have a hello world component so that tag is used.
    You can check Bootstrap integration only with app root tag also.</p>
    <app-hello-world ></app-hello-world>
    </div>
</div>

Now if you access http://localhost:4200/ your template would be rendered as shown in the following image.

Using Bootstrap with Angular

That's all for this topic How to Add Bootstrap to Angular Application. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to Install Node.js and NPM in Windows
  2. How to Setup Angular
  3. Angular Project Structure With File Description
  4. Angular Application Bootstrap Process
  5. Creating New Component in Angular

You may also like-

  1. Installing Anaconda Distribution On Windows
  2. Marker Interface in Java
  3. ArrayList in Java With Examples
  4. PermGen Space Removal in Java 8
  5. Spring Boot Hello World Web Application Example
  6. Spring Boot spring-boot-starter-parent
  7. Java Lambda Expressions Interview Questions And Answers
  8. Compressing File in snappy Format in Hadoop - Java Program