SlideShare a Scribd company logo
Exploring
Angular 2
Ahmed Moawad
Again, with some other Amazing features
Templates
Pipe Operator (|) Templates
Pipes are simple functions that accept an input value and return a transformed value
Example
@Component({ .... })
export class AppComponent{
name: string = “Open Source”;
....
}
<p> Hello, {{ name | uppercase }} </p>
app.component.html
Hello, OPEN SOURCE
app.component.ts
Date Pipe Pipes
date_expression | date[:date_format]
Example
@Component({ .... })
export class AppComponent{
today: number = Date().now();
....
}
<p> Today is {{ today | date: "MM/dd/yy" }} </p>
app.component.html
Today is 02/22/2017
app.component.ts
Decimal Pipe Pipes
number_expression | number[:digitsInfo]
Example
@Component({ .... })
export class AppComponent{
pi: number = 3.1415233455;
....
}
<p> PI: {{ pi | number: ‘1.1-4’ }} </p>
app.component.html
PI: 3.1415
app.component.ts
Safe Navigation Operator (?) Templates
Safe navigation operator (?.) is a fluent and convenient way to guard against null and undefined
values in property paths
Example
@Component({ .... })
export class AppComponent{
movie: any = {name: “up”};
....
}
<p> Movie Name is {{ movie?.name }} </p>
app.component.html
Movie Name is up
app.component.ts
Reference Variables (#) Templates
Reference variable is a reference to a DOM element or directive within a template.
Example
@Component({ .... })
export class AppComponent{
movie: any = “Prestige”;
....
}
<a href=“http://www.google.com” #spy >Google</a>
<p>{{ spy.href }}</p>
app.component.html
Google
http://www.google.com
app.component.ts
The parent of all
Directives
Intro Directives
Templates of the Angular are dynamic, when these templates are rendered by Angular, it
changes the DOM according to the Directive fed instructions.
Directive
{}
Metadata
Types Directives
Directive
{}
Metadata
Component
Structural
Directives
Attributes
Directives
Directives
Structural Directives
*ngFor Structural Directives
@Component({ .... })
export class AppComponent{
movies: string[] = [“Forrest Gump”, “Prestige”, “Up” ]
....
}
<ul>
<li *ngFor=“let m of movies”>
{{ m }}
</li>
</ul>
app.component.html
• Forrest Gump
• Prestige
• Up
app.component.ts
*ngIf Structural Directives
@Component({ .... })
export class AppComponent{
movies: string[] = [“Forrest Gump”, “Prestige”, “Up” ];
movie: string = “Prestige”;
temp = “”;
}
<input [(ngModel)]=“temp” >
<p *ngIf =“temp == movie”>Correct Guess!</p>
app.component.html
app.component.ts
*ngIf Structural Directives
@Component({ .... })
export class AppComponent{
movies: string[] = [“Forrest Gump”, “Prestige”, “Up” ];
movie: string = “Prestige”;
temp = “”;
}
<input [(ngModel)]=“temp” >
<p *ngIf =“temp == movie”>Correct Guess!</p>
app.component.html
Correct Guess!
app.component.ts
Prestige
ngSwitch Structural Directives
Practical Report
Use ngSwitch in Lab
Directives
Attribute Directives
ngClass Attribute Directives
NgClass directive may be the better choice when we want to add or remove many CSS classes
at the same time.
Example
<p [ngClass]=‘setClasses()’>Saveable but not modified</p>
export class AppComponent{
setClasses() {
let classes = { saveable: this.canSave,
modified: this.isModified};
return classes;
}
} // canSave is true, isModified is false.
app.component.html
<p class=“saveable” >Saveable but not modified</p>
app.component.ts
ngStyle Attribute Directives
NgStyle directive may be the better choice when we want to modify many CSS styles at the
same time.
Example
<p [ngStyle]=‘setStyles()’> Hello Open Source </p>
export class AppComponent{
setStyles() {
let styles = { ‘font-style’: this.canSave ? ‘italic’: ‘normal’
‘color’: this.isModified ? ‘orange’: ‘green’
};
return styles;
}
} //canSave is true, isModified is false.
app.component.html
Hello, Open Source
app.component.ts
@Input Attribute Directives
Input directive let the component receive inputs from other components
Example
@Component({
selector: ‘app-movie’,
template:`<p>{{movieName}}</p>`
})
export class MovieComponent{
@Input() movieName;
}
<div>
<app-movie [movieName]=‘movie.name’></app-movie>
</div>
app.component.html
Forrest Gump
movie.component.ts
@Output Attribute Directives
Output directive let the component send data to the other components
Example
@Component({ ... })
export class MovieComponent{
@Output() editMovie = new EventEmitter();
newMovie = {title: ‘The Dark Knight’, Actor: ‘Cristian Pale’ }
ngOnInit(){this.editMovie.emit(this.newMovie) }
//You Can Emit the event anytime you want to send data to the parent component
}
<div>
<app-movie (editMovie)=‘getNewMovie($event)’></app-movie>
</div>
app.component.html
movie.component.ts
A new way to treat with HTML Forms
Forms
Intro Forms
A form creates a cohesive, effective, and compelling
data entry experience.
An Angular form coordinates a set of data-bound user
controls, tracks changes, validates input, and
presents errors.
State Tracker Forms
It tracks every change of the form input state and add a class corresponding to it’s current state.
<form>
<input type="text" id="name" required [(ngModel)] ="movie" name="n">
</form>
Prestige
ng-pristine ng-untouched
ng-invalidng-dirty ng-touched
ng-valid
State Tracker Forms
It tracks every change of the form input state and add a class corresponding to it’s current state.
<form>
<input type="text" id="name" required [(ngModel)] ="movie" name="n">
</form>
Prestige
ng-pristine ng-untouched
ng-invalidng-dirty ng-touched
ng-valid
|
State Tracker Forms
It tracks every change of the form input state and add a class corresponding to it’s current state.
<form>
<input type="text" id="name" required [(ngModel)] ="movie" name="n">
</form>
Prestige
ng-pristine ng-untouched
ng-invalidng-dirty ng-touched
ng-valid
|
State Tracker Forms
It tracks every change of the form input state and add a class corresponding to it’s current state.
<form>
<input type="text" id="name" required [(ngModel)] ="movie" name="n">
</form>
Prestige
ng-pristine ng-untouched
ng-invalidng-dirty ng-touched
ng-valid
|
State Tracker Benefits Forms
.ng-invalid{
border-color: red;
}
Add Custom CSS for every state:1
Add Custom Error messages based on the State:2
<input type="text" id="name" required [(ngModel)] ="movie"
name="name" #name=ngModel>
<div [hidden] =“name.pristine || name.valid”>Input Not Valid</div>
FormsModule Forms
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/core';
import { MovieFormComponent } from './movie-form.component';
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ MovieFormComponent ],
bootstrap: [ MovieFormComponent ]
})
export class AppModule{}
app.module.ts
ngSubmit & ngForm Forms
<form (ngSubmit)=“submitIt()” #movieForm=“ngForm”>
<input type="text" id="name" required name="n">
<input type=“submit" [disabled]=“!movieForm.form.valid”>
</form>
export class MovieFormComponent{
submitted = false;
submitIt() {
//Any other procedures
this.submitted = true;
}
}
movie-form.component.html
movie-form.component.ts
Save
ngSubmit & ngForm Forms
<form (ngSubmit)=“submitIt()” #movieForm=“ngForm”>
<input type="text" id="name" required name="n">
<input type=“submit" [disabled]=“!movieForm.form.valid”>
</form>
export class MovieFormComponent{
submitted = false;
submitIt() {
//Any other procedures
this.submitted = true;
}
}
movie-form.component.html
movie-form.component.ts
Save
Up!
Let’s know more about it’s life
Components
Component Life Cycle
constructor ngOnChanges ngOnInit
ngDoCheck
ngAfterContentInit
ngAfterContentChecked
ngOnDestroy ngAfterViewChecked ngAfterViewInit
Component Life Cycle
constructor ngOnChanges
ngDoCheck
ngAfterContentChecked
ngOnDestroy ngAfterViewChecked
After First Initialization
constructor Component Life Cycle
The constructor for component is called before it is mounted
- constructor is the best place to inject the component
dependencies.
constructor()
Calling Time
Uses
ngOnChanges Component Life Cycle
called when an input binding value changes
- Compare The new input properties to the previous input properties.
- Do action based on the new input properties.
- ngOnChanges doesn’t detect mutable input properties changes.
ngOnChanges(changes: SimpleChanges)
Calling Time
Uses
Notes
SimpleChanges Component Life Cycle
An Object that contains all Component input properties current and previous values
import { Component, SimpleChanges, Input } from '@angular/core';
@Component({ ... })
export class AppComponent {
@Input() movies: string[];
constructor(){};
ngOnChanges(changes: SimpleChanges){
console.log(‘Previous’, changes[‘movies’].previousValue);
console.log(‘Current’, changes[‘movies’].currentValue);
}
}
app.component.ts
ngOnInit Component Life Cycle
called after the first ngOnChanges
- To set up the component after Angular sets the input properties
- We can start using input properties in this life hook because it already
have it’s values now.
- To perform complex initializations shortly after construction.
ngOnInit()
Calling Time
Uses
ngDoCheck Component Life Cycle
is triggered every time the input properties of a component are checked
- to detect and act upon changes that Angular doesn't catch on its own
- our implementation to ngDoCheck must be very lightweight or the
user experience suffers.
ngDoCheck()
Calling Time
Uses
Notes
Content Child & View Child Component Life Cycle
<div>
<app-movie [movieName]=‘movie.name’>
<app-director></app-director >
</app-movie>
</div>
<div>
<p>Movie</p>
<ng-content></ng-content>
</div>
app.component.html
movie.component.html
Movie Component is a View Child to App Component.
Director Component is a Content Child to Movie Component.
View Child
Content Child
Directive that used to project
the Content Child in it’s parent
ngAfterContent Component Life Cycle
called after component child content initialized
- take action based on changing values within the child content
ngAfterContentInit()
Calling Time
Uses
called after every check of component content
- take action based on changing values within the child content
ngAfterContentChecked()
Calling Time
Uses
ContentChild Component Life Cycle
A decorator that create a reference to the instance of a specific child Content
<app-comp>
<app-movie><app-movie>
</app-comp>
index.html
import { Component, ContentChild } from '@angular/core';
@Component({ ...,
template: `<p> Content: <ng-content></ng-content></p>`
})
export class AppComponent {
@ContentChild(MovieComponent) movieComp: MovieComponent;
ngOnContentInit(){console.log(this.movieComp)}
}
app.component.ts
ng-content Component Life Cycle
<div>
<app-movie [movieName]=‘movie.name’>
<app-director></app-director>
<p>Paragraph</p>
<p class=‘red’>Paragraph with Class</p>
</app-movie>
</div>
<p>Content</p>
<ng-content selector=‘p’></ng-content>
<p>Class Content</p>
<ng-content selector=‘.red’></ng-content>
app.component.html
movie.component.html
Content
paragraph
Paragraph with Class
Class Content
Paragraph with Class
output
ngAfterView Component Life Cycle
called after component's child views are initialized
- take action based on changing values within the child view
ngAfterViewInit()
Calling Time
Uses
called after every check of a component's view
- take action based on changing values within the child view
ngAfterViewChecked()
Calling Time
Uses
ViewChild Component Life Cycle
A decorator that create a reference to the instance of a specific child Component
import { Component, ViewChild } from '@angular/core';
@Component({ ... })
export class AppComponent {
@ViewChild(MovieComponent) movieComp: MovieComponent;
constructor(){};
getMovie(m){
this.movieComp.movie = m;
}
}
app.component.ts
ngOnDestroy Component Life Cycle
called just before the component is destroyed
- Do Clean up tasks before component is destroyed
ngOnDestroy()
Calling Time
Uses
Let’s practice what we have learned
Lab
LAB Beginner
Movie DB App : Movies List
Moon Light
La La Land
Prestige
The God Father
Spirited Away
Forrest Gump
Life of PI
Green Mile
LAB Intermediate
Movie DB App : Movie Details
Moon Light
La La Land
Prestige
The God Father
Spirited Away
Forrest Gump
Life of PI
Green Mile
Moon Light
Director: Barry Jenkins
Writer: Tarell Alvin
Actors:
Mahershala Ali,
Shariff Earp,
Duan Sanderson
7.8
LAB Advanced
Movie DB App : Add New Movie
Title
Director
Writer
Rating
Actors
Submit
LAB Bonus
Movie DB App : Edit and Delete Movie
Moon Light
La La Land
Prestige
The God Father
Spirited Away
Forrest Gump
Life of PI
Moon Light
Director: Barry Jenkins
Writer: Tarell Alvin
Actors:
Mahershala Ali,
Shariff Earp,
Duan Sanderson
7.8
edit delete
addMovie DB App
LAB Bonus
Movie DB App : Save Movies on Local Storage
Flash
For the first one that who has completed the
required assignments
Captain America
For the one who has the minimum syntax
errors and his code is well organized
Iron Man
For the one who has the most generic
and strong code
Thor
For the one who find the best and
shortest way to solve the problems
LAB Badges
Thank You
ahmedmowd@gmail.com

More Related Content

PDF
Exploring Angular 2 - Episode 1
Ahmed Moawad
 
PDF
Commit University - Exploring Angular 2
Commit University
 
PDF
Angular 2 Essential Training
Patrick Schroeder
 
PDF
Understanding Angular 2 - Shmuela Jacobs - Codemotion Milan 2016
Codemotion
 
PDF
Angular 2 - The Next Framework
Commit University
 
PPTX
Angular 5
Bartłomiej Narożnik
 
ODP
Introduction to Angular 2
Knoldus Inc.
 
PPTX
Angular js 2
Ran Wahle
 
Exploring Angular 2 - Episode 1
Ahmed Moawad
 
Commit University - Exploring Angular 2
Commit University
 
Angular 2 Essential Training
Patrick Schroeder
 
Understanding Angular 2 - Shmuela Jacobs - Codemotion Milan 2016
Codemotion
 
Angular 2 - The Next Framework
Commit University
 
Introduction to Angular 2
Knoldus Inc.
 
Angular js 2
Ran Wahle
 

What's hot (20)

PDF
Tech Webinar: Angular 2, Introduction to a new framework
Codemotion
 
PPTX
Angular2 + rxjs
Christoffer Noring
 
PPTX
Angular2 for Beginners
Oswald Campesato
 
PDF
Data Flow Patterns in Angular 2 - Sebastian Müller
Sebastian Holstein
 
PDF
Angular2 Development for Java developers
Yakov Fain
 
PDF
Introduction to Angular 2
Naveen Pete
 
PPTX
An afternoon with angular 2
Mike Melusky
 
PDF
Angular Weekend
Troy Miles
 
PDF
Angular 4 for Java Developers
Yakov Fain
 
PDF
Angular 2: core concepts
Codemotion
 
PDF
An introduction to Angular2
Apptension
 
PPTX
Migrating an application from Angular 1 to Angular 2
Ross Dederer
 
PDF
Quick introduction to Angular 4 for AngularJS 1.5 developers
Paweł Żurowski
 
PDF
Intro to JavaScript
Yakov Fain
 
PDF
Seven Versions of One Web Application
Yakov Fain
 
PPTX
Async patterns in javascript
Ran Wahle
 
PDF
Overview of the AngularJS framework
Yakov Fain
 
PPTX
AngularJs presentation
Phan Tuan
 
PPTX
Angular1x and Angular 2 for Beginners
Oswald Campesato
 
PDF
Angular2 with TypeScript
Rohit Bishnoi
 
Tech Webinar: Angular 2, Introduction to a new framework
Codemotion
 
Angular2 + rxjs
Christoffer Noring
 
Angular2 for Beginners
Oswald Campesato
 
Data Flow Patterns in Angular 2 - Sebastian Müller
Sebastian Holstein
 
Angular2 Development for Java developers
Yakov Fain
 
Introduction to Angular 2
Naveen Pete
 
An afternoon with angular 2
Mike Melusky
 
Angular Weekend
Troy Miles
 
Angular 4 for Java Developers
Yakov Fain
 
Angular 2: core concepts
Codemotion
 
An introduction to Angular2
Apptension
 
Migrating an application from Angular 1 to Angular 2
Ross Dederer
 
Quick introduction to Angular 4 for AngularJS 1.5 developers
Paweł Żurowski
 
Intro to JavaScript
Yakov Fain
 
Seven Versions of One Web Application
Yakov Fain
 
Async patterns in javascript
Ran Wahle
 
Overview of the AngularJS framework
Yakov Fain
 
AngularJs presentation
Phan Tuan
 
Angular1x and Angular 2 for Beginners
Oswald Campesato
 
Angular2 with TypeScript
Rohit Bishnoi
 
Ad

Similar to Exploring Angular 2 - Episode 2 (20)

PPTX
yrs of IT experience in enterprise programming
narasimhulum1623
 
PDF
Angular JS2 Training Session #2
Paras Mendiratta
 
PPTX
Angular 2 KTS
John Vall
 
PPTX
Fly High With Angular - How to build an app using Angular
Vacation Labs
 
PDF
Angular 2 overview in 60 minutes
Loiane Groner
 
PPTX
Angular Directives
Malla Reddy University
 
PPTX
Angular 2 in-1
GlobalLogic Ukraine
 
PDF
better-apps-angular-2-day1.pdf and home
ChethanGowda886434
 
PPT
introduction to Angularjs basics
Ravindra K
 
PDF
What is your money doing?
Alfonso Fernández
 
PPTX
Building a TV show with Angular, Bootstrap, and Web Services
David Giard
 
PDF
Instant download Angular 2 Cookbook Frisbie pdf all chapter
ikraanfalan
 
PPTX
Angular Directive.pptx
AshokKumar616995
 
PPTX
Angular Presentation
Adam Moore
 
PPTX
Building maintainable web apps with Angular MS TechDays 2017
Erik van Appeldoorn
 
PDF
Building Blocks of Angular 2 and ASP.NET Core
Levi Fuller
 
PDF
Instant download Angular 2 Cookbook Frisbie pdf all chapter
solvorpohlak24
 
PPTX
Introduction to AngularJs
murtazahaveliwala
 
PDF
Download full ebook of Angular 2 Cookbook Frisbie instant download pdf
kovencoitofm
 
PDF
Angular2 with type script
Ravi Mone
 
yrs of IT experience in enterprise programming
narasimhulum1623
 
Angular JS2 Training Session #2
Paras Mendiratta
 
Angular 2 KTS
John Vall
 
Fly High With Angular - How to build an app using Angular
Vacation Labs
 
Angular 2 overview in 60 minutes
Loiane Groner
 
Angular Directives
Malla Reddy University
 
Angular 2 in-1
GlobalLogic Ukraine
 
better-apps-angular-2-day1.pdf and home
ChethanGowda886434
 
introduction to Angularjs basics
Ravindra K
 
What is your money doing?
Alfonso Fernández
 
Building a TV show with Angular, Bootstrap, and Web Services
David Giard
 
Instant download Angular 2 Cookbook Frisbie pdf all chapter
ikraanfalan
 
Angular Directive.pptx
AshokKumar616995
 
Angular Presentation
Adam Moore
 
Building maintainable web apps with Angular MS TechDays 2017
Erik van Appeldoorn
 
Building Blocks of Angular 2 and ASP.NET Core
Levi Fuller
 
Instant download Angular 2 Cookbook Frisbie pdf all chapter
solvorpohlak24
 
Introduction to AngularJs
murtazahaveliwala
 
Download full ebook of Angular 2 Cookbook Frisbie instant download pdf
kovencoitofm
 
Angular2 with type script
Ravi Mone
 
Ad

Recently uploaded (20)

PDF
Emergency Mustering solutions – A Brief overview
Personnel Tracking
 
PDF
Rise With SAP partner in Mumbai.........
pts464036
 
PDF
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...
Q-Advise
 
PDF
Comprehensive Salesforce Implementation Services.pdf
VALiNTRY360
 
PPTX
10 Hidden App Development Costs That Can Sink Your Startup.pptx
Lunar Web Solution
 
PDF
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
ESUG
 
PDF
QAware_Mario-Leander_Reimer_Architecting and Building a K8s-based AI Platform...
QAware GmbH
 
PDF
A REACT POMODORO TIMER WEB APPLICATION.pdf
Michael624841
 
PDF
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
Hironori Washizaki
 
PPTX
Save Business Costs with CRM Software for Insurance Agents
Insurance Tech Services
 
PDF
Teaching Reproducibility and Embracing Variability: From Floating-Point Exper...
University of Rennes, INSA Rennes, Inria/IRISA, CNRS
 
DOCX
The Future of Smart Factories Why Embedded Analytics Leads the Way
Varsha Nayak
 
PPTX
Presentation of Computer CLASS 2 .pptx
darshilchaudhary558
 
PDF
Appium Automation Testing Tutorial PDF: Learn Mobile Testing in 7 Days
jamescantor38
 
PPTX
Benefits of DCCM for Genesys Contact Center
pointel ivr
 
PDF
Build Multi-agent using Agent Development Kit
FadyIbrahim23
 
PDF
Microsoft Teams Essentials; The pricing and the versions_PDF.pdf
Q-Advise
 
PDF
How to Seamlessly Integrate Salesforce Data Cloud with Marketing Cloud.pdf
NSIQINFOTECH
 
PPTX
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
PPTX
Services offered by Dynamic Solutions in Pakistan
DaniyaalAdeemShibli1
 
Emergency Mustering solutions – A Brief overview
Personnel Tracking
 
Rise With SAP partner in Mumbai.........
pts464036
 
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...
Q-Advise
 
Comprehensive Salesforce Implementation Services.pdf
VALiNTRY360
 
10 Hidden App Development Costs That Can Sink Your Startup.pptx
Lunar Web Solution
 
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
ESUG
 
QAware_Mario-Leander_Reimer_Architecting and Building a K8s-based AI Platform...
QAware GmbH
 
A REACT POMODORO TIMER WEB APPLICATION.pdf
Michael624841
 
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
Hironori Washizaki
 
Save Business Costs with CRM Software for Insurance Agents
Insurance Tech Services
 
Teaching Reproducibility and Embracing Variability: From Floating-Point Exper...
University of Rennes, INSA Rennes, Inria/IRISA, CNRS
 
The Future of Smart Factories Why Embedded Analytics Leads the Way
Varsha Nayak
 
Presentation of Computer CLASS 2 .pptx
darshilchaudhary558
 
Appium Automation Testing Tutorial PDF: Learn Mobile Testing in 7 Days
jamescantor38
 
Benefits of DCCM for Genesys Contact Center
pointel ivr
 
Build Multi-agent using Agent Development Kit
FadyIbrahim23
 
Microsoft Teams Essentials; The pricing and the versions_PDF.pdf
Q-Advise
 
How to Seamlessly Integrate Salesforce Data Cloud with Marketing Cloud.pdf
NSIQINFOTECH
 
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
Services offered by Dynamic Solutions in Pakistan
DaniyaalAdeemShibli1
 

Exploring Angular 2 - Episode 2

  • 2. Again, with some other Amazing features Templates
  • 3. Pipe Operator (|) Templates Pipes are simple functions that accept an input value and return a transformed value Example @Component({ .... }) export class AppComponent{ name: string = “Open Source”; .... } <p> Hello, {{ name | uppercase }} </p> app.component.html Hello, OPEN SOURCE app.component.ts
  • 4. Date Pipe Pipes date_expression | date[:date_format] Example @Component({ .... }) export class AppComponent{ today: number = Date().now(); .... } <p> Today is {{ today | date: "MM/dd/yy" }} </p> app.component.html Today is 02/22/2017 app.component.ts
  • 5. Decimal Pipe Pipes number_expression | number[:digitsInfo] Example @Component({ .... }) export class AppComponent{ pi: number = 3.1415233455; .... } <p> PI: {{ pi | number: ‘1.1-4’ }} </p> app.component.html PI: 3.1415 app.component.ts
  • 6. Safe Navigation Operator (?) Templates Safe navigation operator (?.) is a fluent and convenient way to guard against null and undefined values in property paths Example @Component({ .... }) export class AppComponent{ movie: any = {name: “up”}; .... } <p> Movie Name is {{ movie?.name }} </p> app.component.html Movie Name is up app.component.ts
  • 7. Reference Variables (#) Templates Reference variable is a reference to a DOM element or directive within a template. Example @Component({ .... }) export class AppComponent{ movie: any = “Prestige”; .... } <a href=“http://www.google.com” #spy >Google</a> <p>{{ spy.href }}</p> app.component.html Google http://www.google.com app.component.ts
  • 8. The parent of all Directives
  • 9. Intro Directives Templates of the Angular are dynamic, when these templates are rendered by Angular, it changes the DOM according to the Directive fed instructions. Directive {} Metadata
  • 12. *ngFor Structural Directives @Component({ .... }) export class AppComponent{ movies: string[] = [“Forrest Gump”, “Prestige”, “Up” ] .... } <ul> <li *ngFor=“let m of movies”> {{ m }} </li> </ul> app.component.html • Forrest Gump • Prestige • Up app.component.ts
  • 13. *ngIf Structural Directives @Component({ .... }) export class AppComponent{ movies: string[] = [“Forrest Gump”, “Prestige”, “Up” ]; movie: string = “Prestige”; temp = “”; } <input [(ngModel)]=“temp” > <p *ngIf =“temp == movie”>Correct Guess!</p> app.component.html app.component.ts
  • 14. *ngIf Structural Directives @Component({ .... }) export class AppComponent{ movies: string[] = [“Forrest Gump”, “Prestige”, “Up” ]; movie: string = “Prestige”; temp = “”; } <input [(ngModel)]=“temp” > <p *ngIf =“temp == movie”>Correct Guess!</p> app.component.html Correct Guess! app.component.ts Prestige
  • 15. ngSwitch Structural Directives Practical Report Use ngSwitch in Lab
  • 17. ngClass Attribute Directives NgClass directive may be the better choice when we want to add or remove many CSS classes at the same time. Example <p [ngClass]=‘setClasses()’>Saveable but not modified</p> export class AppComponent{ setClasses() { let classes = { saveable: this.canSave, modified: this.isModified}; return classes; } } // canSave is true, isModified is false. app.component.html <p class=“saveable” >Saveable but not modified</p> app.component.ts
  • 18. ngStyle Attribute Directives NgStyle directive may be the better choice when we want to modify many CSS styles at the same time. Example <p [ngStyle]=‘setStyles()’> Hello Open Source </p> export class AppComponent{ setStyles() { let styles = { ‘font-style’: this.canSave ? ‘italic’: ‘normal’ ‘color’: this.isModified ? ‘orange’: ‘green’ }; return styles; } } //canSave is true, isModified is false. app.component.html Hello, Open Source app.component.ts
  • 19. @Input Attribute Directives Input directive let the component receive inputs from other components Example @Component({ selector: ‘app-movie’, template:`<p>{{movieName}}</p>` }) export class MovieComponent{ @Input() movieName; } <div> <app-movie [movieName]=‘movie.name’></app-movie> </div> app.component.html Forrest Gump movie.component.ts
  • 20. @Output Attribute Directives Output directive let the component send data to the other components Example @Component({ ... }) export class MovieComponent{ @Output() editMovie = new EventEmitter(); newMovie = {title: ‘The Dark Knight’, Actor: ‘Cristian Pale’ } ngOnInit(){this.editMovie.emit(this.newMovie) } //You Can Emit the event anytime you want to send data to the parent component } <div> <app-movie (editMovie)=‘getNewMovie($event)’></app-movie> </div> app.component.html movie.component.ts
  • 21. A new way to treat with HTML Forms Forms
  • 22. Intro Forms A form creates a cohesive, effective, and compelling data entry experience. An Angular form coordinates a set of data-bound user controls, tracks changes, validates input, and presents errors.
  • 23. State Tracker Forms It tracks every change of the form input state and add a class corresponding to it’s current state. <form> <input type="text" id="name" required [(ngModel)] ="movie" name="n"> </form> Prestige ng-pristine ng-untouched ng-invalidng-dirty ng-touched ng-valid
  • 24. State Tracker Forms It tracks every change of the form input state and add a class corresponding to it’s current state. <form> <input type="text" id="name" required [(ngModel)] ="movie" name="n"> </form> Prestige ng-pristine ng-untouched ng-invalidng-dirty ng-touched ng-valid |
  • 25. State Tracker Forms It tracks every change of the form input state and add a class corresponding to it’s current state. <form> <input type="text" id="name" required [(ngModel)] ="movie" name="n"> </form> Prestige ng-pristine ng-untouched ng-invalidng-dirty ng-touched ng-valid |
  • 26. State Tracker Forms It tracks every change of the form input state and add a class corresponding to it’s current state. <form> <input type="text" id="name" required [(ngModel)] ="movie" name="n"> </form> Prestige ng-pristine ng-untouched ng-invalidng-dirty ng-touched ng-valid |
  • 27. State Tracker Benefits Forms .ng-invalid{ border-color: red; } Add Custom CSS for every state:1 Add Custom Error messages based on the State:2 <input type="text" id="name" required [(ngModel)] ="movie" name="name" #name=ngModel> <div [hidden] =“name.pristine || name.valid”>Input Not Valid</div>
  • 28. FormsModule Forms import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/core'; import { MovieFormComponent } from './movie-form.component'; @NgModule({ imports: [ BrowserModule, FormsModule ], declarations: [ MovieFormComponent ], bootstrap: [ MovieFormComponent ] }) export class AppModule{} app.module.ts
  • 29. ngSubmit & ngForm Forms <form (ngSubmit)=“submitIt()” #movieForm=“ngForm”> <input type="text" id="name" required name="n"> <input type=“submit" [disabled]=“!movieForm.form.valid”> </form> export class MovieFormComponent{ submitted = false; submitIt() { //Any other procedures this.submitted = true; } } movie-form.component.html movie-form.component.ts Save
  • 30. ngSubmit & ngForm Forms <form (ngSubmit)=“submitIt()” #movieForm=“ngForm”> <input type="text" id="name" required name="n"> <input type=“submit" [disabled]=“!movieForm.form.valid”> </form> export class MovieFormComponent{ submitted = false; submitIt() { //Any other procedures this.submitted = true; } } movie-form.component.html movie-form.component.ts Save Up!
  • 31. Let’s know more about it’s life Components
  • 32. Component Life Cycle constructor ngOnChanges ngOnInit ngDoCheck ngAfterContentInit ngAfterContentChecked ngOnDestroy ngAfterViewChecked ngAfterViewInit
  • 33. Component Life Cycle constructor ngOnChanges ngDoCheck ngAfterContentChecked ngOnDestroy ngAfterViewChecked After First Initialization
  • 34. constructor Component Life Cycle The constructor for component is called before it is mounted - constructor is the best place to inject the component dependencies. constructor() Calling Time Uses
  • 35. ngOnChanges Component Life Cycle called when an input binding value changes - Compare The new input properties to the previous input properties. - Do action based on the new input properties. - ngOnChanges doesn’t detect mutable input properties changes. ngOnChanges(changes: SimpleChanges) Calling Time Uses Notes
  • 36. SimpleChanges Component Life Cycle An Object that contains all Component input properties current and previous values import { Component, SimpleChanges, Input } from '@angular/core'; @Component({ ... }) export class AppComponent { @Input() movies: string[]; constructor(){}; ngOnChanges(changes: SimpleChanges){ console.log(‘Previous’, changes[‘movies’].previousValue); console.log(‘Current’, changes[‘movies’].currentValue); } } app.component.ts
  • 37. ngOnInit Component Life Cycle called after the first ngOnChanges - To set up the component after Angular sets the input properties - We can start using input properties in this life hook because it already have it’s values now. - To perform complex initializations shortly after construction. ngOnInit() Calling Time Uses
  • 38. ngDoCheck Component Life Cycle is triggered every time the input properties of a component are checked - to detect and act upon changes that Angular doesn't catch on its own - our implementation to ngDoCheck must be very lightweight or the user experience suffers. ngDoCheck() Calling Time Uses Notes
  • 39. Content Child & View Child Component Life Cycle <div> <app-movie [movieName]=‘movie.name’> <app-director></app-director > </app-movie> </div> <div> <p>Movie</p> <ng-content></ng-content> </div> app.component.html movie.component.html Movie Component is a View Child to App Component. Director Component is a Content Child to Movie Component. View Child Content Child Directive that used to project the Content Child in it’s parent
  • 40. ngAfterContent Component Life Cycle called after component child content initialized - take action based on changing values within the child content ngAfterContentInit() Calling Time Uses called after every check of component content - take action based on changing values within the child content ngAfterContentChecked() Calling Time Uses
  • 41. ContentChild Component Life Cycle A decorator that create a reference to the instance of a specific child Content <app-comp> <app-movie><app-movie> </app-comp> index.html import { Component, ContentChild } from '@angular/core'; @Component({ ..., template: `<p> Content: <ng-content></ng-content></p>` }) export class AppComponent { @ContentChild(MovieComponent) movieComp: MovieComponent; ngOnContentInit(){console.log(this.movieComp)} } app.component.ts
  • 42. ng-content Component Life Cycle <div> <app-movie [movieName]=‘movie.name’> <app-director></app-director> <p>Paragraph</p> <p class=‘red’>Paragraph with Class</p> </app-movie> </div> <p>Content</p> <ng-content selector=‘p’></ng-content> <p>Class Content</p> <ng-content selector=‘.red’></ng-content> app.component.html movie.component.html Content paragraph Paragraph with Class Class Content Paragraph with Class output
  • 43. ngAfterView Component Life Cycle called after component's child views are initialized - take action based on changing values within the child view ngAfterViewInit() Calling Time Uses called after every check of a component's view - take action based on changing values within the child view ngAfterViewChecked() Calling Time Uses
  • 44. ViewChild Component Life Cycle A decorator that create a reference to the instance of a specific child Component import { Component, ViewChild } from '@angular/core'; @Component({ ... }) export class AppComponent { @ViewChild(MovieComponent) movieComp: MovieComponent; constructor(){}; getMovie(m){ this.movieComp.movie = m; } } app.component.ts
  • 45. ngOnDestroy Component Life Cycle called just before the component is destroyed - Do Clean up tasks before component is destroyed ngOnDestroy() Calling Time Uses
  • 46. Let’s practice what we have learned Lab
  • 47. LAB Beginner Movie DB App : Movies List Moon Light La La Land Prestige The God Father Spirited Away Forrest Gump Life of PI Green Mile
  • 48. LAB Intermediate Movie DB App : Movie Details Moon Light La La Land Prestige The God Father Spirited Away Forrest Gump Life of PI Green Mile Moon Light Director: Barry Jenkins Writer: Tarell Alvin Actors: Mahershala Ali, Shariff Earp, Duan Sanderson 7.8
  • 49. LAB Advanced Movie DB App : Add New Movie Title Director Writer Rating Actors Submit
  • 50. LAB Bonus Movie DB App : Edit and Delete Movie Moon Light La La Land Prestige The God Father Spirited Away Forrest Gump Life of PI Moon Light Director: Barry Jenkins Writer: Tarell Alvin Actors: Mahershala Ali, Shariff Earp, Duan Sanderson 7.8 edit delete addMovie DB App
  • 51. LAB Bonus Movie DB App : Save Movies on Local Storage
  • 52. Flash For the first one that who has completed the required assignments Captain America For the one who has the minimum syntax errors and his code is well organized Iron Man For the one who has the most generic and strong code Thor For the one who find the best and shortest way to solve the problems LAB Badges