Nested Component Angular

A Component in Angular can have child components. Also, those child components can have their own further child components. Angular seamlessly supports nested components.In this post, we’ll see how to build components designed to be nested within other components and how to establish communication between the nested component and its parent.
Step 1: Create Parent and child Component

child.componet.ts

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

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
@Input() title: string;
  constructor() { }

  ngOnInit() {

  }

}

Step2: Now in template child.componet.html

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

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
  childTitle: string;
  constructor() { }

  ngOnInit() {
    this.childTitle = 'This is message from parent to child';
  }

}

parent.component.html

<div>
<h1>I'm a Parent component</h1>
</div>

child.component.chtml will be:

<h2>{{title}}</h2>

Let’s look at the code again, We’ll using Input property to get the values from the parent.If a nested components wants to receive input from its container, it must expose a property to that container. We use the Input Decorator to decorate any property in the nested components class. In here, we wanna the childTitle pass in the nested component.
Adding input to our import statement

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

If the nested component wants to send information back to its container, it can raise an event. The nested component exposes an event it can use to pass output to its container using the @Output decorator. In this case , the property type must be an event. The only way a nested component can pass data back to its container, is with an event. The data to pass is called the event payload.
So the modified chid.component.ts would be:

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

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
  @Output() notify: EventEmitter = new EventEmitter();
@Input() title: string;
  constructor() { }

  ngOnInit() {

  }
  onClick() {
    this.notify.emit('Click from nested child that subsribe in parent ');
  }
}

You can see I have imported Event Emitter from angularcore
child.component.html

parent.component.ts

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

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

  childTitle: string;
  constructor() { }

  ngOnInit() {
    this.childTitle = 'This is message from parent to child';
  }

  onNotify(message: string): void {
    alert(message);
  }
}

parent.component.html


<div>
  <h1>I'm a Parent component</h1>

</div>

Services in Angular

In real time Angular UI component should focus on presenting data and delegate data access to a service. Services in angular could be singleton and lazy instantiated.services. Singleton service gets created when angular app components need them using $injector. Lets jump directly and create a sample service. We are using public api to get the stock quote and display on UI.

code will looks like stockservice.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class StockService {

  constructor(private http: Http) { }
  getStockPriceLive() {
    return this.http.get('https://www.alphavantage.co/query?function=BATCH_STOCK_QUOTES&symbols=MSFT,FB,AAPL&apikey=demo')
      .map(res => res.json());
  }
}

servicesamplecomponent.ts file looks like:

import { Component, OnInit } from '@angular/core';
import { StockService } from '../stock.service';

@Component({
  selector: 'app-service-sample',
  templateUrl: './service-sample.component.html',
  styleUrls: ['./service-sample.component.css']
})
export class ServiceSampleComponent implements OnInit {
 stock: any[];
  constructor(private stockService: StockService) { }

  ngOnInit() {
    this.getLiveStockPrice();
  }

  getLiveStockPrice() {
    this.stockService.getStockPriceLive().subscribe((result) => {
      console.log(result['Stock Quotes']);
      this.stock = result['Stock Quotes'];

    });
  }
}

Now display on UI:
Screen Shot 2018-03-11 at 2.07.57 PM
As we can see we created a stock service for loosely-coupled communication between classes.The StockService injected into a component is created with another component, Service sample.HttpClient is Angular’s mechanism for communicating with a remote server over HTTP. HttpClient.get returns the body of the response as an untyped JSON object by default. Next sample we will try to make API call that returns an observable collection of objects.

 

Angular 5 Sample 1

First Angular 5 sample code in VS Code. This code sample will maintain an array of object customers locally and search button will demonstrate how we can attach an event and how to use a stractureal directive (*ngFor) in angular. I have created a component called detail.
The cod ein detail.component.ts:

 import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-detail',
  templateUrl: './detail.component.html',
  styleUrls: ['./detail.component.css']
})
export class DetailComponent implements OnInit {
  customers: any[];
  public LoadCustomers(filterText: string): void {
    this.customers = [
      { id: 1, Name: 'Tom Paul' },
      { id: 2, Name: 'John Doe' },
      { id: 3, Name: 'Jijo Venginikkadan' },
      { id: 4, Name: 'Alex George' },
    ];

    if (filterText !== '') {
      const filteCustomerList: any[] = [];
      this.customers.forEach(cust => {
        console.log(cust.Name);
        console.log(filterText);
        if (cust.Name.toLowerCase().includes(filterText.toLowerCase())) {
          filteCustomerList.push(cust);
        }
      });
      this.customers = filteCustomerList;
    }
  }
  constructor() { }

  ngOnInit() {
    this.LoadCustomers('');
  }
  OnCustomerSearch(searchTerm: string): void {
    console.log(searchTerm);
    this.LoadCustomers(searchTerm);
  }

}

Template detail.component.html would looks like:

<div class="form-group">
  <div class="md-col-4">
    Enter Student Name:
  </div>
  <div class="md-col-4">
    
  </div>
</div>

  Search

<table class="table table-responsive table-bordered table-striped">
  <thead>
    <tr>
      <th>Customer ID</th>
      <th>Name</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>{{s.id}}</td>
      <td>{{s.Name | uppercase}}</td>
    </tr>
  </tbody>
</table>