Using LocalReference

  • Instead of two-way binding, we can easily fetch a value of any input through┬álocal references in Angular
  • Lets create a demo project to see an example of it.

First create a demo project in angular using angular CLI

Make changes in the app.component.html file as below :

    <label>Enter text here</label>
    <input type="text"#textBoxRef>
    <button (click)="onButtonClick(textBoxRef)">Click Me</button>
    <p>The text entered in the text box is {{msg}}</p>
    <!--<p>{{textBoxRef.value}} will also provide the same value</p> -->

Make below changes into the app.component.ts file.

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'LocalReferenceDemo';
  msg: string;
  onButtonClick(textBox : HTMLInputElement){
    this.msg = textBox.value;
  }
}

Ouput will some like this :

A Sample application displaying Parent and Child communication

Create a project in Angular using Angular CLI and create two component named filter and table

ng new DemoApplication
ng g c filter
ng g c table

Edit app.module.ts file as below : Adding forms module :

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { FilterComponent } from './filter/filter.component';
import { TableComponent } from './table/table.component';

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

Edit app.component.html as below :

<div class="container">
  <app-filter
  (mammelAdded)="onMammelAdded($event)"
  (birdAdded)="onBirdAdded($event)"
  ></app-filter>
  <hr>
    <app-table *ngFor="let animal of animals"
    [animalElement]="animal"></app-table>
</div>

Edit app.component.ts as below :

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  animals = [
    {
      animalName: 'Cheeta',
      category: 'Mammal'
    }
  ];
  onMammelAdded(animalData: {animalName: string, category: string}) {
    this.animals.push({
      animalName: animalData.animalName,
      category: 'Mammel'
    });
  }
  onBirdAdded(animalData: {animalName: string, category: string}) {
    this.animals.push({
      animalName: animalData.animalName,
      category: 'Bird'
    });
  }
}

Edit filter.component.html as below :

<div class="row">
  <div class="col-xs-12">
    <h3>Add new Animal !</h3>
    <label>Animal Name</label>
    <input type="text" class="form-control" [(ngModel)]="animalName" >
    <br>
    <button type="button" class="btn btn-success btn-sm mr-1" (click)="onBirdAdded()">Add Bird</button>
    <button type="button" class="btn btn-info btn-sm mr-1" (click)="onMammelAdded()">Add Mammal</button>
  </div>
</div>

Edit filter.component.ts file as below :

<div class="row">
  <div class="col-xs-12">
    <h3>Add new Animal !</h3>
    <label>Animal Name</label>
    <input type="text" class="form-control" [(ngModel)]="animalName" >
    <br>
    <button type="button" class="btn btn-success btn-sm mr-1" (click)="onBirdAdded()">Add Bird</button>
    <button type="button" class="btn btn-info btn-sm mr-1" (click)="onMammelAdded()">Add Mammal</button>
  </div>
</div>

Edit table.component.html as below :

<table class="table table-dark">
  <thead>
    <tr>
      <th scope="col">Animal Name</th>
      <th scope="col">Animal Category</th>
    </tr>
  </thead>
<tbody>
  <tr>
    <!-- <td>{{i+1}}</td> -->
    <td>{{animalElement.animalName}}</td>
    <td>{{animalElement.category}}</td>
  </tr>
</tbody>
</table>

Edit table.component.ts as below :

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

@Component({
  selector: 'app-table',
  templateUrl: './table.component.html',
  styleUrls: ['./table.component.css']
})
export class TableComponent implements OnInit {

  @Input()
  animalElement: {animalName: string, category: string};

  constructor() { }

  ngOnInit() {
  }
}

The output of the application looks like below :

ngFor Directive

To understand ngFor lets create a new Angular project using angular CLI

Write the below contents in app.component.html file

<h2>List of colors</h2>
<ul *ngFor="let color of colors">
  <li>{{color}}</li>
</ul>
<h2>Displaying colors using index of ngFor</h2>
<div *ngFor="let color of colors; let i = index">
  <p>{{i+1}} - {{color}}</p>
</div>

Write the below contents into app.component.ts file

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'ngForDemo';
  colors = ['Read','Yellow','Blue','Green'];
}

After running the code on server the output will look like below :

ngClass Directive

To demonstrate ngClass directive we first create an angular project using angular CLI.

Write the below contents in app.component.html file

<h1> ng Class Demo</h1>
<button (click)="onButtonClick()" >Click me to change Style Clas</button>
<p [ngClass]="{defaultCss : toggle==true}">Hello World, the color of this paragraph changes with button click</p>

Write the below contents in app.component.ts file

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styles: [`
      .defaultCss{
        color : white;
        background-color : maroon;
      }
  `]
})
export class AppComponent {
  title = 'ngClassDemo';
  toggle = false;
  onButtonClick(){
    if(this.toggle) {
      this.toggle = false;

    } else{
      this.toggle = true;
    }
  }
}

And the output looks like below : On button click the class is applied to the paragraph tag

ngStyle Directive

  • ngStyle is a attribute directive
  • Unlike Structural directive, attribute directive does not add or remove elements but only change the elements they are placed on.

Lets create a new angular project using angular CLI and make below changes in app.component.html file

<H3>Change Button color</H3>
<button (click)="onButtonClick()" [ngStyle]="{backgroundColor : myColor}">Change Color</button>

Make the below changes in app.component.ts file

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'ngIfElseDemo';
  myColor = 'green';
  onButtonClick(){
    this.myColor = Math.random() > 0.5 ? 'pink' : 'yellow';
  }
}

And the output will look like below :

lsof Command (List Of Open Files)

The lsof output describes:

  • the identification number of the process (PID) that has opened the file;
  • the process group identification number (PGID) of the process (optional);
  • the process identification number of the parent process (PPID) (optional);
  • the command the process is executing;
  • the owner of the process;
  • for all files in use by the process, including the executing text file and the shared libraries it is using:
    • the file descriptor number of the file, if applicable;
    • the file’s access mode;
    • the file’s lock status;
    • the file’s device numbers;
    • the file’s inode number;
    • the file’s size or offset;
    • the name of the file system containing the file;
    • any available components of the file’s path name;
    • the names of the file’s stream components;
    • the file’s local and remote network addresses;
    • the TLI network (typically UDP) state of the file;
    • the TCP state, read queue length, and write queue length of the file;
    • the file’s TCP window read and write lengths (Solaris only); and
    • other file or dialect-specific values.

Search for the process which is listening of a particular port :

sudo lsof -i:4200

Search for the process and kill it using below command :

sudo kill $(sudo lsof -t -i:4200)

ngIf with an else Condition

  • ngIF is a Structural directive and else part is just an add on to it.
  • This means it changes the structure of the dom using it hence its always represented with a * (start) ahead of it
  • Lets create a new Angular project using Angular CLI for this example
  • Add the following code in app.component.html file
<H1>Hello User</H1>
<button (click)="onButtonClick()">Toggle Me</button>
<p *ngIf="isButtonClicked; else noButtonClicked">The button is clicked</p>
<ng-template #noButtonClicked>
<p>The button is not clicked</p>
</ng-template>

Add the following code in app.component.ts file

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'ngIfElseDemo';
  isButtonClicked = false;
  onButtonClick(){
    if(this.isButtonClicked){
      this.isButtonClicked = false;
    }else{
      this.isButtonClicked = true;
    }
  }
}

Output looks like below :

ngIf Directive

  • ngIF is a Structural directive
  • This means it changes the structure of the dom using it hence its always represented with a * (start) ahead of it
  • Create a new Angular Project using CLI, and make changes to app.component.html as below :
<H1>Greet User</H1>
<button (click)="onButtonClick()">Greet</button>
<div *ngIf="isGreet">
  <h3>{{msg}}</h3>
</div>

Make Changes to the app.component.ts as below :

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'ngIfDemo';
  isGreet: boolean = false;
  msg: string = 'Hi! , Greetings fellow viewer';
  onButtonClick(){
    if(this.isGreet){
      this.isGreet = false;
    } else{
      this.isGreet = true;
    }
   }
}

And the output looks like below : On button toggle the text is displayed.

Directives in Angular

  • Directives are instructions in the dom.
  • When we place a directive in a html, we are directing angular, to display a template instead of the directive along with its business logic in our TypeScript code.
  • Types of directives in Angular are
    • Component Directive
    • Attribute Directive
    • Structural Directive
      • ngIf Directive
      • ngIf else directive
    • Form Directive
  • Some of the built in Angular directives are
    • ng-template
    • ngStyle directive
    • ngClass directive
    • ngFor directive

Two way data binding

  • To understand Two way binding we will first create a sample project using angular CLI
  • Then we need to add FormsModule in the app.module.ts file to enable the ngForm directive in our template/html.
  • After making changes to app.module.ts file, the file will have details.
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

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

We need to modify app.component.html as below

<p>Enter the text below</p>
**** Line 1 ****One way Event Binding : <input type="text" (input)="onTextInput($event)"/><br/><br/>
**** Line 2 ****<b>Two Way Binding</b> : <input type="text" [(ngModel)]="textMsg"/><br/><br/>
**** Line 3 ****String Interpolation The text entered in the textbox is : {{textMsg}}

We need to modify app.component.ts file as below

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  textMsg : string;
  onTextInput(event : Event){
    this.textMsg = (event.target as HTMLInputElement).value;
  }
}

The output after making all the changes looks like below

  • Line1 Textbox, Line2 Textbox and Line3 String linked to the same property textMsg in our TypeScript
  • Now on Line1 we have used one way event binding i.e on each keypress in the textbox of line1 the value is passed through the method onTextInput() and stored in the textMsg property defined in our TypeScript code.
    • As we change the textbox value on Line 1, the textbox value of Line2 and String on line3 change since line2 textbox and line3 string are binded with the property textMsg
  • Now on Line2 we have used two way binding i.e on each keypress in the textbox of lin2 the value is passed through to the textMsg property of TypeScript class AppComponent implicitly using ngForm directive.
    • Hence as we change the value on line2 textbox the value of String on Line3 change accordingly since we are reading the value of the textMsg property on Line3.
  • Thus we can conclude that
    • line1 textbox only write the value to textMsg property but not read because of one way binding
    • line2 textbox can read and write the value from and to textMsg property because of two way binding
    • line3 string can only read the value from textMsg property since it is displayed using StringInterpolation.