Communication pattern between parent and child using Subject services
16th Jul 19 10:09 am    admin

Angular now a days they use Observable’s convention to Promises and callbacks. By using subject angular could store data dynamically during runtime. Subject is one type of observable that implement shared services to be communicated to any layer of components. To use this services we need to create injectable service using angular.

Consider we have two components the main component which is app.component.ts and another component which may be parent or child component subject-data.component.ts. Create a component using angular cli tools. Now our aim is to create a services and share between component. Create a service in angular using ng g s data here data is a service name. This will create a service class angular file data.service.ts and data.service.spec.ts. Right Now our focus is the service class file and not testing file. Consider the below service file data.service.ts

import { Injectable } from '@angular/core';
import { Subject, Observable } from 'rxjs';

@Injectable()
export class DataService {
  private messageSource = new Subject<String>();
  constructor() { }
  public getMessage(): Observable<String> {
    return this.messageSource.asObservable();
  }
  public setMessage(mesg: String) {
    this.messageSource.next(mesg);
  }
}

In the above we created an instance of Subject which should be of type String. Now Create Two function getMessage() which should be returning of observable type. setMessage(msg) where msg should be passed as a string and using next method we pass what is the next data to be passed into the stream. As soon as set message is set here data get changed. In order to view the message the particular component should Inject the service in the constructor using Dependency Injection in angular.

If the particular service is injected in constructor. Then, we can use those methods in our components and call those methods. Consider the subject-data.component.ts below we have injected the service in constructor and call those methods and we indicated as subscribe as to get the data from the observable. Only when we subscribe data could be subscribed from the stream.

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';

@Component({
  selector: 'app-subject-data',
  templateUrl: './subject-data.component.html',
  styleUrls: ['./subject-data.component.css']
})
export class SubjectDataComponent implements OnInit {
  message: String;
  constructor(private data: DataService) { }

  ngOnInit() {
    console.log("Loading Subject data....");
      this.data.getMessage().subscribe(message => this.message = message);
      console.log(this.message);
  }

}

Consider subject-data.component.html here whenever data gets changed i.e message indicated will display the value

<p>
 {{message}}
</p>

Consider the app.component.html

<app-subject-data></app-subject-data>
<button (click)="updateSubject()">Update Subject</button>

In the above code we have subject component and button.

import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'angular-data-sharing';
  constructor(private data: DataService) { }
  ngOnInit() {
    console.log("Loading App data....");
  }
  updateSubject() {
    this.data.setMessage(this.title);
  }
}

Whenever we Click the button, we set the value. As soon as we set value data is shared between all component to which it has been injected and a change has been reflected.

Angular
Observable
RxJS
Subject
Show More
What is Angular ?
12th Jul 19 6:43 am    srinivasanvelu23

Angular is front end javascript framework for building rich user interface applications. Angular Version 1 are totally based on pure javascript and in order to work with angular 1 we need to link external javascript files. But this is not case with version 2, angular javascript way of coding has completely replace by Typescript. Typescript are the way of writing javascript in the sense of object oriented programming.

Angular 8 – latest stable version

Today majority of browser support es5, so typescript based programming can convert any advanced javascript to browser supported version i.e. es5.

But, there are so far many version have released till date and current version of angular is 8. Angular have change its way of developing project as modules and components. This helps to maintain cleaner code and reuse the existing components. Unit testing also can be done, because of its loosely coupled components and modules.

Angular
Show More
Communication pattern between Parent and Child using @Input
4th Jul 19 6:33 am    srinivasanvelu23

There are many ways that we can communicate from parent to child or share the data. We will discuss briefly as we proceed one by one.

 

Using @Input decorator

We use @input decorator in the child component class by 

@Input('data') value:any;

In the parent class component we declare attribute binding with For eg., like this format in tag [inputData] to pass data.

 <posts [data]="posts"></posts>

Let us discuss this with the small example having parent class as parent.component.ts and child class as child.component.ts.

Step 1 – Create a new app using ng new app-name

But before performing this operation you should have installed angular CLI tools. Invoking this command in command prompt will create an angular app with default folder structure, which will help us to maintain a cleaner code.

Step 2 – Create a parent Component using ng g c parent

This will create a component with the html, stylesheet (scss, css, sass, less), typescript, spec(Unit testing). Repeat the same procedure for creating the child component as ng g c child

This will create a two directory parent and child like mentioned below:

Folder structure of parent and child

App Component is the starting point of angular application. In app.component.html we indicated a selector parent as

<app-parent></app-parent>

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 {
  parent: any;
  constructor() { }

  ngOnInit() {
    this.parent = 'Sample App';
  }
}

In parent.component.ts we have declared a variable of type any. And on component initialization on ngOnInit a typescript variable is assigned the value. In parent.component.html below

<app-child [data]="parent"></app-child>

In the above html code app-child refers to child component selector which we have given when creating component. Each component html page is identified by selector in component.ts file. [data] represent input attribute because some data needs to be inputted.

child.component.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 {
// tslint:disable-next-line: no-input-rename
  @Input('data') data: any;
  constructor() { }

  ngOnInit() {
  }

}

Here in the above code, in the child.component.ts @Input refers to data to be based to child component.

<p>
  {{data}}
</p>

The above is child.component.html where data is passed to child which when displayed in html emit the assigned value. This is how we pass the data from the parent to child using @Input decorator.

@input decorator
Angular
Communication patterns
passing the data from parent to child
Show More
Newsletter

Subscribe below and we'll send you a weekly email summary of your updates which you