Component in Angular | by ByteCode Pandit

Components

Components are the very basic building block UI element in angular applications. They are directives with a special decorator (@Component) and template. Component decorator allows you to mark a class as an Angular component and provide additional metadata that determines how the component should be processed, instantiated, and used at runtime. Below is an example of a basic component:

import { Component } from '@angular/core';@Component({
selector: 'hello-component',
templateUrl: './hello-component.html',
styleUrls: ['./hello-component.css']
})
class Greet {
public name: string = 'Component';
}

You can easily use this component anywhere in the application buys just including like this <hello-component></hello-component>.

Component Life Cycle hooks

Components can control their run-time behaviour by implementing various Life-Cycle hooks. The main life-cycle are following.

ngOnChanges: Respond when Angular sets or resets data-bound input properties.

ngOnInit: Initialize the directive or component after Angular first displays the data-bound properties and set the directive or component's input properties.

ngDoCheck: Detect and act upon changes that Angular can't or won't detect on its own.

ngAfterContentInit: Respond after Angular projects external content into the component's view, or into the view that a directive is in.

ngAfterContentChecked: Respond after Angular checks the content projected into the directive or component.

ngAfterViewInit: Respond after Angular initializes the component's views and child views, or the view that contains the directive.

ngAfterViewChecked: Respond after Angular checks the component's views and child views, or the view that contains the directive

ngOnDestroy: Cleanup just before Angular destroys the directive or component. Unsubscribe Observables and detach event handlers to avoid memory leaks.

Components relationship

Angular is built up of many components. There is a root component that serves as the parent component, every other component can be called a Child Component to the root component since the root component is the Parent Component.


Sharing data between components

To share the data between components in angular, we need to define the kind of relationship that exists between the components, because help us to determine the best way to share data between the components. 

Parent to Child: The easiest way to pass data from parent to child is to use the @Input binding which allows data to be shared via the template like below:

//parent.component.tsimport { Component } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'parent-component',
template: `
<child-component [messageToChild]="parentMessage">
</child-component>
`,
styleUrls: ['./parent.component.css']
})
export class ParentComponent {
parentMessage = "message from parent";
constructor() {};
}
//child.component.tsimport { Component } from '@angular/core';
import { ParentComponent } from './parent.component';
@Component({
selector: 'child-component',
template: `
{{ childMessage }}
`,
styleUrls: ['./parent.component.css']
})
export class ChildComponent {
@Input() childMessage: string;
constructor() {};
}


Child to Parent: The @Output decorator is used to emit data out of a component to a parent component.
import { Component, Output, EventEmitter } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'child-component',
template: `
<button (click)="sendMessageToParent()">
Send Message To Parent
</button>
`,
styleUrls: ['./child.component.css']
})
class ChildComponent {
@Output() messageFromChild = new EventEmitter();

sendMessageToParent() {
this.messageFromChild.emit('Message from child');
}
}

@Component({
selector: 'parent-component',
template: `
<child-component (messageFromChild)="onMessageRecieved($event)">
</child-component>
`,
styleUrls: ['./parent.component.css']
})
class ParentComponent {

onMessageRecieved(event) {
console.log(event);
}
}


Siblings(directly unrelated components): To share the data between the no-related components we use the service.


//data.service.tsimport { Injectable } from '@angular/core';@Injectable()
export class DataService {
}
//componentA.component.tsimport { Component } from '@angular/core';
import { DataService } from './data.service';
@Component({
...
...
})
export Class ComponentA {
constructor(public dataService: DataService) {}
get data():string {
return this.dataService.serviceData();
}
set data(value: string) {
this.dataService.setDate = value;
}
}
//componentB.component.tsimport { Component } from '@angular/core';
import { DataService } from './data.service';
@Component({
...
...
})
export Class ComponentB {
constructor(public dataService: DataService) {}
get data():string {
return this.dataService.serviceData();
}
set data(value: string) {
this.dataService.setDate = value;
}
}


Thanks for your kind attention, pls share and comment if you like this post !!


Comments

Popular posts from this blog

Real-Life Use-Cases for useCallback and useMemo

React's useImperativeHandle with practical example | by ByteCode Pandit

Understand NgModule in 15 mins | by Bytecode Pandit