To pass data between components at the same level under parent, I.E. passing data between two children within the same parent we use @Input and @Output and pass the value through the tags.

The Other option is using EventEmitter as variable in Service and emitting value from component1 and getting value in component2.

  1. In the below code we are passing data from list-person.component.ts to add-person.component.ts
  2. We are calling instance of personcrudService to call a function which emits event which is received by ListPersonComponent OnInit() method
  3. In add-person.component.ts we subscribe to the event by using instance of personcrudService

personcrud.service.ts

import {EventEmitter, Injectable, OnInit} from '@angular/core';
import {LoggingServiceService} from './logging-service.service';

@Injectable({
  providedIn: 'root'
})
export class PersoncrudService{  
  statusUpdated: EventEmitter<string> = new EventEmitter<string>();

  constructor(public loggingServiceService: LoggingServiceService) {}

  updatePerson(id: number, status: boolean){
    .
    . 
    this.statusUpdated.emit(this.arrPersons[id].name);
    .
    .
  }
}

list-person.component.ts

@Component({
  selector: 'app-list-person',
  templateUrl: './list-person.component.html',
  styleUrls: ['./list-person.component.css'],
  providers: [LoggingServiceService]
})
export class ListPersonComponent implements OnInit {
  constructor(private personcrudService: PersoncrudService,
              private loggingServiceService: LoggingServiceService) { }

  ngOnInit(): void {
  }

  updateStatus(i, status){
    this.personcrudService.updatePerson(i, status);
    this.loggingServiceService.logStatusOfPerson(status);
  }
}

add-person.component.ts

@Component({
  selector: 'app-add-person',
  templateUrl: './add-person.component.html',
  styleUrls: ['./add-person.component.css']
})
export class AddPersonComponent implements OnInit {
  constructor(private personcrudService: PersoncrudService) {
  }

  ngOnInit(): void {
    this.personcrudService.statusUpdated.subscribe(
      (name: string) => alert(name + ' has been updates')
    );
  }
}

Find the Minimum and Maximum Sum

Input Format
A single line of five space-separated integers.

Constraints

    \[1<arr[i]<10^9\]

Output Format
Print two space-separated long integers denoting the respective minimum and maximum values.

Sample Input

1 2 3 4 5

Sample Output

10 14
  1. Find the Minimum and Maximum Element in array
  2. When you calculate the minSum and maxSum – discard the maxElement and minElement
  3. Trick is you may miss logic if the array contains 5 elements and all are of same value. In such case the maximum and minimum value elements are same
  4. For finding minimum number, start by assigning maximum number to minNum
.
.
 public static void miniMaxSum(List<Integer> arr) {
        long minNum = 0;
        long maxNum = 0;

        long minSum = 0;
        long maxSum = 0;


        //To find maximum Number
        for(int num=0;num<arr.size();num++){
            if(maxNum<=arr.get(num)){
                maxNum = arr.get(num);
            }
        }

        //To find minimum Number
        minNum = maxNum;

        for(int num=0;num<arr.size();num++){
            if(arr.get(num)<=minNum){
                minNum = arr.get(num);
            }
        }

        for(int num=0;num<arr.size();num++){
            //If the array elements are of same value
            if(num!=0 && arr.get(num) == arr.get(num-1)){
                minSum +=arr.get(num);
                maxSum +=arr.get(num);
            }


            if(arr.get(num) != maxNum)
              minSum +=arr.get(num);

            if(arr.get(num) != minNum)
              maxSum +=arr.get(num);
        }

        System.out.println(minSum);
        System.out.println(maxSum);
    }
.
.

Get Count of biggest Element in array – Total Tallest Candles to be blown

Input Format
Array of Integers

Constraints

    \[1<candles[i]<10^7\]

Output Format
Count of Biggest Element in array

Sample Input

3 2 1 3 5 6 5 4 5

Sample Output

1
  1. In the above example 6 is the biggest element and it occurs only once
  2. Find the biggest element in array
  3. Find the count of the biggest element
public static int birthdayCakeCandles(List<Integer> candles) {
        // Write your code here
        long tallestCandle = 0;
        int tallestCandleCnt = 0;

        for(int num=0;num<candles.size();num++){
            if(tallestCandle<=candles.get(num)){
                tallestCandle = candles.get(num);
            }
        }

        for(int num=0;num<candles.size();num++){
            if(candles.get(num) == tallestCandle)
                tallestCandleCnt +=1;
        }

        return tallestCandleCnt;
    }

How to Delete duplicate Rows from Table

In the below table studId 1,6 and 9 is repeated which should be deleted.

studId studentName age
1 Mugil 35
2 Vinu 36
3 Viju 42
4 Mani 35
5 Madhu 36
6 Mugil 35
7 Venu 37
8 Banu 34
9 Mugil 35

Below query wont work on MySQL but the format doesn’t change. When you take Max only last occurrence of row would be taken and others would be excluded.

DELETE FROM tblStudents TS
 WHERE TS.studId NOT IN (SELECT MAX(TSS.studId)
                            FROM tblStudents TSS
                        GROUP BY TSS.studentName, TSS.age)c

The same could be done using MIN function.

SELECT TS.* FROM tblStudents TS
 WHERE TS.studId NOT IN (SELECT MIN(TSS.studId)
                           FROM tblStudents TSS
                          GROUP BY TSS.studentName, TSS.age)                        

Output

studId studentName age
6 Mugil 35
9 Mugil 35

We use property binding to pass value from component to form element in html and event binding to pass value from html to angular component.

  1. In the below code when we use [value] to get the value from component to html
  2. The same way we use (input) to get back value on event like change of name text
  3. {{employee.Name}} is used to display the value. You can remove [value] or (input) to check the behavior.
  4. Instead of this we can use ngModule by importing FormsModule which takes care of both propery and data binding

empform.html

<form>
<input type="text" [value]="employee.Name" (input)="employee.Name=$event.target.value" />
{{employee.Name}}
</form>

EmployeeModel.ts

export class Employee {
  private _Name: String;

  constructor(name: String) {
    this._Name = name;
  }
}

EmployeeController.ts

export class AddemployeeComponent implements OnInit {
.
.
  public employee: Employee;

  constructor() {
    this.employee = new Employee('Mugilvannan');
  }
.
.
}

  1. For NgModeul to work name attribute(i.e. employeeName) is mandatory in form field.
    Otherwise the value wont be reflected on change
  2. [ngModel] is for value binding and (ngModelChange) is for event binding. Both can be grouped in to format called banana-in-a-box. [(ngModel)]
  3. For using ngModel, FormsModule should be added to app.module.ts
  4. So when to use expanded syntax of ngModel. There would be times where you want to change the text into uppercase or lowercase once it is entered into textbox or formfields. In suchcase we should call an event which does it. At that time you would use (ngModelChange) instead of [(ngModel)].

addemployee.component.html

  <form>
    <table style="border-collapse:collapse;" border="1" cellpadding="5">
      <tbody>
        <tr>
          <td>Name</td>
          <td><input type="text" name="employeeName" [ngModel]="employee.Name" (ngModelChange)="employee.Name=$event" /></td>
        </tr>
        <tr>
          <td colspan="2">
            <input type="submit" value="Add Employee" (click)="employee.Name='test'" />
          </td>
        </tr>
      </tbody>
    </table>
  </form>
  {{employee.Name}}

addemployee.component.html – Banana-in-a-Box format

.
.
<td><input type="text" name="employeeName" [(ngModel)]="employee.Name"/></td>
.
.
  1. Services are mostly used in displaying datas from APIs
  2. To generate a new service use ng generate service Services/SERVICE_NAME
  3. services are injectable because they would be mostly called by other components
  4. Injection of services can happen at three level
    • AppModule – Same Instance of Service Injected would be available across application
    • AppComponent – Same Instance of Service Injected at this level would be available in this component and all child component
    • Any Other Component – Same Instance of Service Injected would be available to this component and child component(not to parent component)
  5. @Injectable is not needed if the Service is added in app.modules.ts

aboutus.component.ts

.
.
constructor(private objApi:ApiService) { 
    this.objApi.getDataFromRest();
  }
.
.

api.service.ts

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

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  constructor() { }

  getDataFromRest()
  {
    return console.log("Data from Rest Method");
  }
}

If Else
aboutus.component.ts

export class AboutusComponent implements OnInit {
  showMsg: boolean = true;
  .
  .
  .
}

aboutus.component.html

<p *ngIf='showMsg; else elseBlock'>aboutus works from If block!</p>

<ng-template #elseBlock>
    <p>aboutus works from else block!</p>
</ng-template>

Output

aboutus works from If block!

Switch Case
aboutus.component.ts

export class AboutusComponent implements OnInit {
  .
  .
  color : string =  'pink';
  .
  .
}

aboutus.component.html

<div [ngSwitch] = 'color'>
    <p *ngSwitchCase="'blue'">Its Blue Color</p>
    <p *ngSwitchCase="'red'">Its Red Color</p>
    <p *ngSwitchCase="'green'">Its Green Color</p>    
    <p *ngSwitchDefault>Its Default Color</p>    
</div>

Output

Its Default Color

For Angular routing the routing option should have been enabled while starting new project.

  1. To define a link you need to use routerLink instead of href followed by route in other side of equals like one in app.component.html
      <ul>
        <li><a routerLink="/">Home</a></li>
        <li><a routerLink="/aboutus">About Us</a></li>
        <li><a routerLink="/services">Services</a></li>
        <li><a routerLink="/contactus">Contact Us</a></li>
      </ul>
    
  2. The list of routes needs to be defined in app-routing.module.ts. It is defined inside routes array list with path and component as key value pair like one below app-routing.module.ts
    const routes: Routes = [
      {path:'aboutus', component: AboutusComponent},
      {path:'services', component: ServicesComponent},
      {path:'contactus', component:ContactComponent}
    ];
    
  3. The path and one defined assigned to routerLink in html should be same. The component is the name of the component class which represent individual page of application
  4. If you are using absolute path then it would be /PATH which takes reference of component to be loaded form root url. If you are using relative path the it would be PATH (or) ../PATH (or) ../../PATH. Incase you are using relative path clicking the link of the same page from the page you are in should throw an error(Could not be verified)
  5. Navigating to link could be acheived by two ways
    • Using RouterLink in a tags
    • Using router navigate method in ts code
  6. routerLink always knows which route is currently loaded.router navigate method does not which route is presently loaded. So we always use activateRoute and pass relativeTo as parameter and pass relative URL as parameter

app-routing.module.ts

import { NgModule, Component } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {AboutusComponent} from './aboutus/aboutus.component';
import {ServicesComponent} from './services/services.component';
import {ContactComponent} from './contact/contact.component';


const routes: Routes = [
  {path:'aboutus', component: AboutusComponent},
  {path:'services', component: ServicesComponent},
  {path:'contactus', component:ContactComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

app.component.html

<style>
ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}

li {
  float: left;
}

li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

/* Change the link color to #111 (black) on hover */
li a:hover {
  background-color: #111;
}

.active {
  background-color: #4CAF50;
}

li {
  border-right: 1px solid #bbb;
}

li:last-child {
  border-right: none;
}
</style>
<div class="content" role="main">
  <ul>
    <li><a routerLink="/">Home</a></li>
    <li><a routerLink="/aboutus">About Us</a></li>
    <li><a routerLink="/services">Services</a></li>
    <li><a routerLink="/contactus">Contact Us</a></li>
  </ul>
</div>
<router-outlet></router-outlet>

Code Snippets – Table of Contents

  1. Builtin Angular Directives

    1. Attribute Directive – NgStyle, NgClass
    2. Structural Directive – *NgIf, *NgFor, *NgSwitch

Attribute Directive – ngClass and ngStyle
ngClass

  1. For using ngClass the styling should be in JSON Obect
  2. Advantage of using ngClass is applying more than one class to the DOM Element unlike class
  3. In the below code you see class which applies present or absent based on one true or false returned by getResult function
  4. In the registration.component.ts we have declared a JSON object which applies 2 classes present and normal or absent and bold based on true or false returned by getStatus(method)

Styling using class
registration.component.html

.
.
<td [class]="getStatus()?'present':'absent'">{{objStudent.science}}</td>
.
.
.

Styling using ngClass
registration.component.html

.
.
<td [ngclass]="cssStyle">{{objStudent.science}}</td>
.
.
.

registration.component.ts

.
.
export class RegistrationComponent implements OnInit { 
  public cssStyle;  
 
  ngOnInit() {
     this.cssStyle = {
       "present" : getStatus(),
       "absent"  : !getStatus(),
       "normal"  : getStatus()
       "bold"    : !getStatus(),       
     };
  }
}

.
.
.

ngStyle

  1. ngStyle is to apply style directly instead of defining style using class
  2. Same registration.component.ts has been modified to take style attributed such as color and weight

registration.component.ts

.
.
export class RegistrationComponent implements OnInit { 
  public cssStyle;  
 
  ngOnInit() {
     this.cssStyle = {
       "background-color"  : getStatus()?"green":"red",
       "font-weight"       : getStatus()?"normal":"bold"       
     };
  }
}
.
.
.

There is an alternative for both above [class] and [ngClass] as below

.
.
<td [class.positive]="getStatus()" [class.negative]="!getStatus()">{{objStudent.science}}</td>.
.

Similarly for [ngStyle] as below

.
.
<td [style.background-color]="getStatus()?'green':'red'">{{objStudent.science}}</td>.
.

Structural Directive – ngIf, ngFor and ngSwitch
ngIf

  1. In the below code we decide the words to be displayed based on the value returned by getStatus(objStudent) method
  2. Pass would be displayed if true or else fail would be returned
.
.
<span *ngIf="getStatus(objStudent)">Pass</span>
<span *ngIf="!getStatus(objStudent)">Fail</span>
.

ngFor

  1. In the below code we use *ngFor loop to iterate over array of student object
  2. We are generating serial no for first column by adding 1 to variable i and displaying name of student in second column
  3. *ngFor has other loacl values apart from indes such as even, odd, first, last based on which manipulations could be carried out

registration.component.ts

.
.
export class RegistrationComponent implements OnInit {
  public arrStudent:Array<Student>;

  ngOnInit() {
     this.arrStudent = [new Student(101, 'Mugil', 31, 74, 65,55,64,84),
                        new Student(102, 'Manasa', 26, 31, 65,55,86,84),
                        new Student(103, 'Kavitha', 27, 90, 65,60,84,46),
                        new Student(104, 'Renu', 28, 31, 65,55,84,46),
                        new Student(105, 'Joseph', 23, 31, 65,55,89,84)];

  }
.
.
}

registration.component.ts

.
.
<tr>
    <th>Sno</th>
    <th>Student ID</th>
</tr>
<tbody>
  <tr *ngFor="let objStudent of arrStudent; index as i;">
     <td>{{i+1}}</td>
     <td>{{objStudent.studentId}}</td>
     .
     .
     .
     .
  </tr>
</tbody>
.
.

Now let’s see a simple example of applying a different color to text based on odd and even rows

registration.component.ts

.
.
<tr *ngFor="let objStudent of arrStudent; index as i;odd as isOdd; even as isEven" [class]="isOdd?'odd':'even'">
     .
     <td>{{i+1}}</td>
     <td>{{objStudent.studentId}}</td>
     .
</tr>

the same code can be written as below where the only difference is styles are applied seperately evaluating for both odd and even.
registration.component.ts

.
.
<tr *ngFor="let objStudent of arrStudent; index as i;odd as isOdd; even as isEven" [class]="isOdd" [class.even]="isEven">
     .
     <td>{{i+1}}</td>
     <td>{{objStudent.studentId}}</td>
     .
</tr>

We can define the template directly in a component instead of giving the templateURL using a template and define styleURL instead of styles.

registration.component.ts

.
.
@Component({
  selector: 'app-registration',
  template: '<tr>
              <td>{{objStudent.studentId}}</td>
              <td>{{objStudent.studentName}}</td>
            </tr>',
  styleUrls: ['./registration.component.css']
})
.
.
.

registration.component.ts

.
.
@Component({
  selector    : 'app-registration',
  templateURL : 'app-registration.html',
  styles      : ['
                   .present
                   {
                      background-color: greenyellow;
                   }

                   .absent
                   {
                      background-color: #fc8674;
                   }
                ']
})
.
.
.

Interpolation
app.component.ts

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

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

registration.component.html

<div style="text-align:center">
  <h1>
    Welcome to {{ title }}!
  </h1>
</div>

Looping through Model Object set in component and Printing in HTML Page
Student.ts

export class Student {
   public isPresent:boolean=true;

   constructor(public studentId:number,
               public studentName:string,
               public studentAge:number,
               public studentGender:boolean){}
               

    getAttendance():string{
       if(this.isPresent==true)
        return "P";
       else 
        return "A";
    }           
}

registration.component.ts

import { Component, OnInit } from '@angular/core';
import {Student} from '../model/student';

@Component({
  selector: 'app-registration',
  templateUrl: './registration.component.html',
  styleUrls: ['./registration.component.css']
})
export class RegistrationComponent implements OnInit {
  public arrStudent:Array<Student>;
  constructor() { }

  ngOnInit() {
     this.arrStudent = [new Student(101, 'Mugil', 31, true),
                        new Student(102, 'Manasa', 26, false),
                        new Student(103, 'Kavitha', 27, false),
                        new Student(104, 'Renu', 28, true),
                        new Student(105, 'Joseph', 23, true)];
  }

  getGender(Student):string
  {
    if(Student.studentGender==true)
     return "M";
     else
     return "F";
  }
}

registration.component.html

<style>
 .even
    {
        background-color: rgb(235, 235, 235);
    }

    .odd
    {
        background-color : #ffffff;
    }
</style>
<table cellpadding="5">
    <thead>
  <tr>
    <th>Sno</th>
    <th>Student ID</th>
    <th>Name</th>
    <th>Age</th>
    <th>Gender</th>
    <th>Attendance</th>
  </tr>
</thead>
<tbody>
  <tr *ngFor="let objStudent of arrStudent; index as i;even as isEven;odd as isOdd" [class]="isEven?'even':'odd'">
     <td>{{i+1}}</td>
     <td>{{objStudent.studentId}}</td>
     <td>{{objStudent.studentName}}</td>
     <td>{{objStudent.studentAge}}</td>
     <td>{{ getGender(objStudent) }}</td>
     <td [class]="objStudent.isPresent?'present':'absent'">{{objStudent.getAttendance()}}</td> 
  </tr>
</tbody>
</table>


	

Bootstrapping Angular Application

  1. Then entry point to every Angular application is the main.ts file which contains this last line:
     
     platformBrowserDynamic().bootstrapModule(AppModule); 
    
  2. The platformBrowserDynamic() part of this line of code indicates that we are about to boot Angular in a browser environment. As Angular can be used in Javascript host environments asides the browser (e.g. on the server or in a web worker), its thus imperative that we specify the environment in which our App is to be booted.
  3. The bootstrapModule() function helps bootstrap our root module taking in the root module as its argument.
  4. AppModule is our root module which is the entry module for our application, this can actually be any of the modules in our application but by convention AppModule is used as the root module.
  5. In our AppModule, we then need to specify the component that will serve as the entry point component for our application. This happens in our app.module.ts file where we import the entry component (conventionally AppComponent) and supply it as the only item in our bootstrap array inside the NgModule configuration object.
     
     bootstrap:[AppComponent]
    

To put it short

  1. platformBrowserDynamic() to determine the Broswer or platform in which your angular app is about to run
  2. bootstrapModule() function to boot your entry module(app.module.ts) by supplying the module as an argument.
  3. app.module.ts is the root module that would specify the entry point component in the module configuration object.

How angular Works Internally