Getting into Component of Angular
Deep Understanding of Components in Angular
The anatomy of the Component is very straightforward, it has component class and template. They are wired together using Metadata which is mainly very simple in most of the cases.
Outside of the structure piece we have communication channels which basically happens through Event Binding and Property Binding.
Let’s be clear here using class does not equate to inheritance.
Component Class
- Create the component as an ES6 class
- Properties and methods on our component class will be available for binding in our template.
// By using export we define our classes so we can use it elsewhere
export class AppComponent {
title = 'stating-point';
}
Import
It helps to get access to dependencies that we want in current file:
- Import the core dependencies
- Import 3rd party dependencies
- Import your custom dependencies
This approach gives us a more fine-grained control over the managing our dependencies
Import only those dependencies which are useful for your program. For example RxJS has 150 dependencies so let’s say we need 5 out of those for our need. So no need to import whole RxJS here.
// Like here we are importing only Component from angular/core
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
Class Decoration
- We turn our class into something that Angular can easily use by decorating it with Angular specific metadata
- We can use the @Component syntax to decorate our classes.
- We can also decorate methods and properties inside our class.
- The two most common decorators are @Input and @Output.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'stating-point';
}
And now after all that we need to expose this component. So simply we can do that using @NgModule.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
@NgModule({
declarations: [
AppComponent,
HomeComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Lifecycle Hooks
In the lifespan of the components, there are numerous things that can happen, and that we want to know about.
Examples:
- Is the template rendered?
- Is the class initialized?
and many others.
- During the various stages of component’s life span we can perform custom logic using hooks.
- One of the most common use case is when the data is not currently available for the constructor.
- Implemented as class methods on the component class.
- Unless we are writing unit tests, we should not call them.
- The lifecycle interfaces are optional but it will count as a strong typing in TypeScript and better for developers.
List of Lifecycle Hooks
- ngOnChanges: called when an input or output binding value changes
- ngOnInit: called after the first ngOnChanges
- ngDoCheck: handles developer’s custom change detection
- ngAfterContentInit: called after component content initialized
- ngAfterContentChecked: called after every check of component content
- ngAfterViewInit: called after component’s view(s) are initialized
- ngAfterViewChecked: called after every check of a component’s view(s)
- ngOnDestroy: called just before the directive is destroyed
Out of all above written we are mainly going to use ngOnInit and ngOnDestroy the most.
export class LoginComponent implements OnInit {
userInfo: UserInfo = {
email: '',
password: '',
};
constructor(private authService: AuthService) {}
ngOnInit(): void {}
login(userInfo: UserInfo) {
this.authService.login(userInfo);
}
}
Property Binding
Property binding in Angular helps you set values for properties of HTML elements or directives.
- Flows data from component to an element.
- Created with brackets <img [src]=”image.src” />
- There are special cases for binding to attributes,classes and styles that look like [attr.property], [class.className], and [style.styleName] respectively.
<span [style.color]="componentStyle">Some Colored Text!</span>
Event Binding
Event binding lets you listen for and respond to user actions such as keystrokes, mouse movements, clicks, and touches.
- Flows data from element to the component.
- Created with parenthesis <button (click)=”foo($event)”></button>.
- Information about the target event is carried in the $event parameter.
<button ype="button" (click)="save.emit(selectedItem)">Save</button>
Two-way Binding
Two-way binding gives components in your application a way to share data. Use two-way binding to listen for events and update values simultaneously between parent and child components.
- Really just a combination of property and event binding
- Used in conjunction with ngModel
- Usually referred to as “banana in a box”
<label>The awesome input</label>
<input [(ngModel)]="dynamicValue" placeholder="Watch the text update!" type="text">
<label>The awesome output</label>
<span>{{dynamicValue}}</span>
Structural Directives
- A structural directive changes the DOM layout by adding and removing DOM elements.
- Asterisks indicate a directive that modifies the HTML.
- It is syntactic sugar to avoid having to use template elements directly.
<div *ngIf="hero">{{hero}}</div>
<div *ngFor="let hero of heroes">{{hero}}</div>
<span [ngSwitch]="toeChoice">
<span *ngSwitchCase="'Eenie'">Eenie</span>
<span *ngSwitchCase="'Meanie'">Meanie</span>
<span *ngSwitchCase="'Miney'">Miney</span>
<span *ngSwitchCase="'Moe'">Moe</span>
<span *ngSwitchDefault>other</span>
</span>
Local Template Variable
If you want to reference a piece of your template somewhere else inside of the template then you can use Local Template Variable.
- The hashtag(#) defines a local variable inside our template
- We can refer to a local template variable anywhere in the current template
- To consume, simple use it as a variable without the hashtag
- The canonical form of #hashtag is ref-variable
<span *ngIf="currentPortfolio.id; else prompt">Editing {{originalName}}</span>
<ng-template #prompt>Create</ng-template>
Safe Navigation Operator
- Denoted by a question mark immediately followed by a period e.g. “?.”
- If you reference a property in your template that does not exist., you will throw an exception.
- The safe navigation operator is simple, easy way to guard againt null and undefined properties.
<h2>The null hero's name is {{nullHero?.firstName}}</h2>
With all this, let’s end this blog as this is it of Getting into Components of Angular. If you will find any issue regarding concept or code, you can message me on my Twitter or LinkedIn. The next blog will be published on 11 March 2023.
Some words about me
I’m Mohit.❤️ You can also call me Chessman. I’m a Machine learning Developer and a competitive programmer. Most of my time is spent staring at a computer screen. During the day, I am usually programming, working to derive insight from large datasets. My skills include Data Analysis, Data Visualization, Machine learning, Deep Learning, DevOps and working toward Full Stack. I have developed a strong acumen for problem-solving, and I enjoy occasional challenges.