Components and Data Binding: The Building Blocks of Our Application
Components and Data Binding: The Building Blocks of Our Application
SoftUni Team
Technical Trainers
Software University
https://softuni.bg
Table of Contents
2
Questions
sli.do
#js-web
3
Components: Basic Idea
The Main Building Block
The Idea Behind Components
A component controls part of the screen (the view)
You define application logic into the component
Each component has its own HTML/CSS template
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `<h1>{{title}}</h1>`,
styles: [ `h1 {
background-color: red;}` ]
Unique html template
}) and styling
Components can
Article Component
interact with each other
6
Creating Components
And Their Unique Templates
Creating Components Manually
To create a component we need the Component
decorator
import { Component } from '@angular/core';
8
Creating Components Manually
Component Metadata
selector - the component's HTML selector
selector: 'app-home'
11
Bootstrapping
Starting the Application
Bootstrapping an Application
An NgModule class describes how the application parts
fit together
Every application has at least one NgModule – the root
module
platformBrowserDynamic().bootstrapModule(AppModule)
13
The Initial Module
@NgModule({
declarations: [ AppComponent ], The @NgModule tells
imports: [ BrowserModule ], Angular how to compile
providers: [], and launch the app
bootstrap: [ AppComponent ]
})
14
Initial Module Properties
The declarations array
Only declarables – (components, directives and pipes)
The imports array
Only @NgModule classes – integrated (HttpClientModule,
BrowserModule) or custom made
15
Initial Module Properties
The providers array
Register service providers and inject them into components
The bootstrap array
The root component – used to launch the application
Inserting a bootstrapped component
usually triggers a cascade of component creation
16
Data Bindings & Templates
Repeater, Enhanced Syntax
Templates & Data Bindings Overview
A template is a form of HTML that tells Angular how to
render the component
render array properties using *ngFor repeater
render nested properties of an object
condition statements using *ngIf
attach events and handle them in the component
They can be both inline or in a separate file
18
Render an Array Using *NgFor
export class GamesComponent {
games : Game[];
constructor() {
this.games = [ // Array of games ]
}
}
<h1>Games List</h1>
<p>Pick a game to Buy</p>
<ul>
<li *ngFor="let game of games">
{{game.title}}
The '*' symbol is
</li>
required in front
</ul>
19
Conditional Statements Using *NgIf
<h1>Games List</h1>
<p>Pick a game to Buy</p>
<ul>
<li *ngFor="let game of games">
<div>
{{game.title}}
</div>
<span *ngIf="game.price >= 100">->
Price: {{game.price}}
</span>
</li>
</ul>
20
Attach Events
<button (click)="showContent($event)">Show Content</button>
constructor() {
this.games = [ // Array of games ]
}
showAdditionalContent($event) {
this.showContent = true;
}
}
21
Binding Attributes
Binding attributes
export class GamesComponent {
imgUrl: string;
constructor() {
this.imgUrl = "a url to an image"
}
}
Binding classes
<div [class]="badCurly">Bad curly</div>
23
Binding Styles or Styles with Units
Binding styles
<button [style.color]="isSpecial ? 'red': 'green'">Red</button>
<button [style.background-color]="canSave ? 'cyan': 'grey'" >
Save
</button>
24
Reference and Null-safe Operator
Reference other elements
<input #phone placeholder="phone number">
<button (click)="callPhone(phone.value)">Call</button>
25
Template Expressions
The text between the curly brackets is evaluated to a string
<p>The sum of two + two + four is {{2 + 2 + 4}}</p>
29
NgOnInit and NgOnDestroy Example
import { Component, OnInit, OnDestroy } from '@angular/core';
@Component({..})
export class GamesComponent implements OnInit, OnDestroy {
games: Game[];
ngOnInit() {
console.log('CREATED'); Called shortly after creation
}
ngOnDestroy() {
console.log('DELETED'); Used for cleanup
}
}
30
Other Lifecycle Hooks
All lifecycle hooks
ngOnChanges() - when data is changed
ngDoCheck() - detect your own changes
ngAfterContentInit() - when external content is received
ngAfterContentChecked() - when external content is checked
ngAfterViewInit() - when the views and child views are created
ngAfterViewChecked() - when the above are checked
More at: https://angular.io/guide/lifecycle-hooks
31
Component Interaction
Passing Data in Between
From Parent to Child
<h1>Games List</h1>
<p>Pick a game to Buy</p> Render the child into the
<ul> parent template and
<game *ngFor="let game of games" pass the needed prop
[gameProp]="game">
</game>
</ul>
<button (click)="showAdditionalContent()">Show Image</button>
34
Component Interaction
In order to pass data from child to parent component
we need the Output decorator and an Event Emitter
import { Output, EventEmitter } from '@angular/core';
export class GameComponent {
@Input('gameProp') game : Game;
@Output() onReacted = new EventEmitter<boolean>();
react(isLiked : boolean) {
this.onReacted.emit(isLiked);
}
} The parent will receive the event
35
Component Interaction
The Parent component handles the event
<game *ngFor="let game of games="[gameProp]"="game"
(onReacted)="onReacted($event)">
</game>
Each
… component has its own template
@Component({ selector: 'app', template:
…
`<h1>{{title}}</h1`})
There
… are three types of data binding
We can intersect the lifecycle of a component
ngOnInit() { this.data = // Retrieve data }
37
Questions?
© SoftUni – https://softuni.org. Copyrighted document. Unauthorized copy, reproduction or use is not permitted.
SoftUni Diamond Partners
39
SoftUni Organizational Partners
40
Trainings @ Software University (SoftUni)
Software University – High-Quality Education,
Profession and Job for Software Developers
softuni.bg, softuni.org
Software University Foundation
softuni.foundation
Software University @ Facebook
facebook.com/SoftwareUniversity
Software University Forums
forum.softuni.bg
41
License
42