0% found this document useful (0 votes)
131 views17 pages

(BOOK Notes) Ng-Book

This document provides instructions for creating a basic Angular application with multiple components. It discusses: 1. Using the Angular CLI to generate components and add metadata like selectors, templates, and styles. 2. Creating arrays of data in components and iterating over them in templates using *ngFor. 3. Passing data between parent and child components using @Input. 4. Bootstrapping the application by specifying the root component in AppModule and rendering it. 5. Binding input values to variables and passing them into methods. 6. Applying styles to component hosts using @HostBinding.

Uploaded by

Toby Yu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
131 views17 pages

(BOOK Notes) Ng-Book

This document provides instructions for creating a basic Angular application with multiple components. It discusses: 1. Using the Angular CLI to generate components and add metadata like selectors, templates, and styles. 2. Creating arrays of data in components and iterating over them in templates using *ngFor. 3. Passing data between parent and child components using @Input. 4. Bootstrapping the application by specifying the root component in AppModule and rendering it. 5. Binding input values to variables and passing them into methods. 6. Applying styles to component hosts using @HostBinding.

Uploaded by

Toby Yu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

1.

Writing 1st app


1.1. Npm node package manager, installed as part of node.js

code/first-app/angular-hello-world/src/index.html
<body>
<app-root></app-root>
</body>
</html>
The app-root tag is where our application will be rendered.
1.2. Component
1.2.1. Command: ng generate component name
Create single component
code/first-app/angular-hello-world/src/app/hello- Ts document component control
world/hello-world.component.ts
import { Component, OnInit } from '@angular/core'; Import dependencies from the module
@angular/core
Import{things} - destructing (ES6 and
Typescript)
OnInit: help initiate when run component
@Component({ Component decorators
selector: 'app-hello-world',
templateUrl: './hello-world.component.html', Metadata added to the code
styleUrls: ['./hello-world.component.css'] Decorating the class to be a component
})
Selector: define a new tag in makup.
Defint which DOM element this
component uses.
Template: load template form html to
index.html. Can add by specify url or just
add html elements
Style: style only apply to the component
export class HelloWorldComponent implements Declare and set property type
OnInit {
Name: string ; // declare property of class Constructor: function called when create
constructor() { new instance of this class
this.name = 'Felipe';
}
ngOnInit() {

Create array of elements in a single component


 Declare array of values in .ts component as a
property
 Iterate over the list of items using *ngFor
attribute in comp-name.component.html
/src/app/user-list/user-list.component.ts {{ expression }}
export class UserListComponent implements OnInit { Expression in html of the component is
names: string[]; tied to component class value
constructor() {
this.names = ['Ari', 'Carlos', 'Felipe', 'Nate']; *ngFor = “let item-name of collection-
} name”:
Create a new DOM element for every
/src/app/user-item/user-item.component.html item in a collection
<ul> <li *ngFor="let name of names">Hello {{expression name}} need to follow
{{ name }}</li> </ul> single-item name

Pass value to child component through @Input and [child component @input variable]
 Render template in child-component.html
 Accept inputs: configure in .ts
 Pass input value
/app/user-list/user-list.component.html [parent] Pass from parent to child through @input
<li *ngFor="let single-name of names"> Render child-component in parent-
<app-user-item [name]="single-name"></app-user- template. Call components list
item>
</li> [name]=”single-name”: each app-user-
item component name property accept
value from single-name property of
parent
/app/user-item/user-item.component.ts [child] @input decorator: allow passing value
import {Input} from ‘@angular/core’; from a parent component
export class UserItemComponent implements OnInit {
@Input() name: string; }

1. Iterating over names [collections created in user-list.ts] parent component is user-list


2. Creating a new UserItemComponent for each element in names and
3. Passing the value of that name into the name Input property on the UserItemComponent

1.2.2. Component is used by input selector tag in app.component .html


1.3. Bootstrapping
1.3.1. angular.json specifies a "main" file, which in this case is main.ts
1.3.2. • main.ts is the entry-point for our app and it bootstraps our application
1.3.3. • The bootstrap process boots an Angular module
1.3.4. • We use the AppModule to bootstrap the app. AppModule is specified in
src/app/app.module.ts
1.3.5. • AppModule specifies which component to use as the top-level
component. In this case it is AppComponent
1.3.6. • AppComponent has <app-user-list> tags in the template and this renders our
list of users.
/src/app/app.module.ts
@NgModule({ @NgModule( ... ) code
declarations: [ adds metadata to the class
AppComponent, immediately following
HelloWorldComponent,
UserItemComponent, declarations
UserListComponent declarations specifies the
], components that are
imports: [ defined in this module.
BrowserModule
], imports
providers: [], imports describes which
bootstrap: [AppComponent] dependencies this module
}) has.
export class AppModule { } providers
providers is used for
dependency injection.
bootstrap
bootstrap tells Angular that
when this module is used to
bootstrap an app, we need
to load the
AppComponent component as
the top-level component.

1.4. Passing input in form


src/app/app.component.html

<div class="field"> <input name="title" #newtitle>


<label for="title">Title:</label> bind this <input> to the variable
<input name="title" #newtitle> newtitle. The #newtitle syntax
</div> is called a resolve. The effect is
<div class="field"> that this makes the variable
<label for="link">Link:</label> newtitle available to the
<input name="link" #newlink> expressions
</div> within this view.
<button (click)="addArticle(newtitle, newlink)" newtitle is now an object that
class="ui positive right floated button"> represents this input DOM element
Submit link (specifically, the type is
</button> HTMLInputElement).
we get the value of the input tag
using newtitle.value.

button (click)="addArticle(newtitle,
newlink)"
Pass value by reference

App.component.ts #newtitle is a resolve and the type is


HTMLInputElement. It is an object,
addArticle(title: HTMLInputElement, link: need to call value as title.value
HTMLInputElement): boolean {
console.log(`Adding article title: ${title.value} and link: $
{link.value}`);
return false;

<a href (click)="voteUp()"> (event)=”function to be called” as an


attribute
/src/app/article/article.component.ts In Angular, a component host is
export class ArticleComponent implements OnInit { the element this component is
@HostBinding('attr.class') cssClass = 'row'; attached to. We can set
properties
Equivalent to on the host element by using the
App.component.html (host element of the article- @HostBinding() decorator.
component)
<app-article 'attr.class'=’row’></app-article>

Event handler propagation control


voteDown(): boolean { JS propagate event click to all parent
this.votes -= 1; elements. As it can propagate to an
return false; empty link input in the form, the
browser would be triggered to reload.

To avoid reloading, add return false to


control the event handler to stop.
constructor(title: string, link: string, votes?: number) { Votes?: number ? means optional
this.title = title; property to construct
this.link = link;
this.votes = votes || 0; || 0, by default set value to 0
}
Try catch function
Expect to return string type
Err: all errors

1.5. Value passing method


Pass value from .ts to .html {{expression}} Same component
Template binding
App.html {{expression can be a
<p> {{title }} </p> function}}
App.ts
Export Class appcomponent {
Title: string // declare variable
Constructor() {this.title=”expression value”}
}
Pass value from parent component .html to child component .ts @Input module import

Parent.html
<div>
<child-component
[child-variable]=”parent-element-name”></child-component>
</div>

Child.ts
Import input from @angular/core
Export class child component {
@Input child-variable: type; // declare input variable to accept value
}
Pass value within html view Add resolve within the
<input name=”title” #titleresolve>title</input> same view

<button (click)=”addvote(titleresolve)”>voteup</button>
1.6. Deployment
1.6.1. Deploying our app is the act of pushing our code to a server, where it can be
accessed by others.
1.6.2. • compile all of our TypeScript code into JavaScript (which the browser can
read)
1.6.3. • bundle all of our JavaScript code files into one or two files
1.6.4. • and then upload our JavaScript, HTML, CSS, and images to a server
1.6.5. Ultimately, this Angular app is an HTML file that loads JavaScript code.
2. Typescript
2.1. There are five big improvements that TypeScript bring over ES5:
2.1.1. • types
2.1.1.1. Advantage:
2.1.1.2. Prevent bugs at compile time during writing
2.1.1.3. Clarification of intention during reading.
2.1.2. • classes
2.1.3. • decorators
2.1.4. • imports
2.1.5. • language utilities (e.g. destructuring)
Declaring type
var fullName: string;
function greetText(name: string): string {
return "Hello " + name; }

2.2. Types (special ones)


2.2.1. Enum
enum Role {Employee, Manager, Admin};
var role: Role = Role.Employee;
Assign role belongs to Role enum type and has the value Employee
enum Role {Employee = 3, Manager, Admin};
var role: Role = Role.Employee;
Enum starts at 3, followed by 4, 5
enum Role {Employee = 3, Manager = 5, Admin = 7};
var role: Role = Role.Employee;
enum Role {Employee, Manager, Admin};
console.log('Roles: ', Role[0], ',', Role[1], 'and', Role[2]);
Enum collection Role can be treated as an array, start from 0.

2.2.2. Any
any is the default type if we omit typing for a given variable. Having a variable of
type any allows it to receive any kind of value:

2.2.3. Void
Using void means there’s no type expected. This is usually in functions with no
return value:
2.3. Classes
2.3.1. Properties
2.3.2. Methods: functions called in context of object. Need first initiate an instance of
class first
2.3.3. Constructor: a special method that is executed when a new instance of the
class is being created.
2.3.3.1. Constructor methods must be named constructor.
2.3.3.2. Can take in parameters but not return any value
2.3.4. Inheritance
Child class extends
super class existing
behaviour

Super(child-class
parameters)
Construct super class
based on given
parameters

Super.run()
Call super class
methods

Super(parameters):
construct an
instance of super-
class object

2.4. Utilities
2.4.1. Fat arrow function syntax
2.4.1.1. Function (input){actions;} can be shortened to input => action
2.4.1.2. => syntax shares the same this. As the surrounding code.
This.name refers to “nate”
as => syntax use same this
reference as the
surrounding

2.4.2. Template strings


2.4.2.1. Variables in strings/string interpolation. No “+” needed to concatenate
string
2.4.2.2. Template strings for multiple lines

3. How Angular works


3.1. Overview: a tree of components. Top-level application booted first, then recursively
renders child components
3.2. Components
3.2.1. @Component decorator
3.2.1.1. Selector, tells Angular what element to match
<inventory-app-root></inventory-app-root>
<div inventory-app-root></div>
3.2.1.2. Template or templateUrl, defines the view
3.2.2. A view
3.2.3. A controller, defined by class
3.2.4. Input definition: [input variable of a component] = “expression which value will
be passed to input”
3.2.4.1. In .ts controller, property @Input specify the parameters we expect our
component to receive.
[class.selected]="isSelecte
d(myProduct)"
Pass value to input
conditionally
“add the CSS class
selected
if isSelected(myProduct)
returns true

3.2.5. Output definition: (name of output listened )=”function called when something
new is sent to the output($event is a special variable represents the thing sent
to the output)”
1. Specify outputs in the @Component configuration
2. Attach an EventEmitter to the output property
3. Emit an event from the EventEmitter, at the right time
3.2.5.1. EventEmitter:
3.2.5.1.1. Maintain a list of subscribers
3.2.5.1.2. Publish events to them
1. Specify output
and type of
output[declaration]
2. Create instance
when component is
called [construction]
3. Emit output
method [action]

(single-component
output/ child
component
property)= “outside
property or method
from club
component/ parent
component
($output event from
child component)”

$event from method


“putRingOnit” from
single-component
putRingOnit
eventemitter

$event is passed to
ringWasPlaced as
message

3.2.6. Ternary operator


3.2.6.1. test ? valueIfTrue : valueIfFalse
3.3. Ng serve process
• ng serve looks at .angular-cli.json which specifies main.ts as our entry point (and
index.html as our index file)
• main.ts bootstraps AppModule
• AppModule specifies that AppComponent is the top level component
• … and then AppComponent renders the rest of our app!
3.4. Conditional style for elements
/Style.css Define the css style when an element is
.classname.selected{ style specs} selected
Component.html [class.selected] class is the inherited css class
“expression” can be a conditional statement or
<div class="ui items"> a function to return a Boolean value
    <product-row Only when the return value is true, the css
        *ngFor="let myProduct of productList" style is adopted. Once event changes, style
        [product]="myProduct" returns to default.
        (click) ='clicked(myProduct)'

        [class.selected]="isSelected(myProduct)"> Click event=> clicked function set current


    </product-row> product => isSelected() check if product-row is
</div> the currentProduct across all iterated list

3.5. Data architecture


3.5.1. One-way data binding instead of two-way
3.5.2. Data flows only down through components.
3.5.3. Changes required, emit events to change at “higher levels” and trickle down
3.5.4. Avoid complications in change detection and make the system more readable
4. Built-in directives [handle output dynamic data]
4.1. Definition: attributes added to HTML elements to support dynamic behaviour
NgIf Display or hide an element based on a condition determined by the result of
the expression

NgSwitch Render different elements depending on a given condition


create[ngSwitch]=”control expression”
• Describe the known results, using the ngSwitchCase directive
• Handle all the other unknown cases with ngSwitchDefault. Optional. If left
out, other cases will have nothing rendered
NgStyle Set DOM element CSS properties

[style.<cssproperty>]="value"
<div [style.background-color]=" 'yellow' ">

Single quote to mark value for CSS properties and values

<span [ngStyle]="{color: 'red'}" [style.font-size.px]="fontSize">


[style.font-size.px] px is included to specify unit as px
[style.font-size.em]
[style.font-size.%]

<div [style.background-color]="color"
style="color: white;">
{{ color }} background
</div>

Style vs [style]
NgClass <div [ngClass]="{bordered: false}"> static class
<div [ngClass]="{bordered: isBordered}"> dynamic class by object literal
<div [ngClass]="classesObj"> dynamic class by object that represents {bordered:
true/false}
NgFor Repeat a given DOM element(or a collection) and pass an element of the
array
*ngFor="let item of items; let variable-name = index"
• The let item syntax specifies a (template) variable that’s receiving each
element of the items array;
• The items is the collection of items from your controller.
Component.ts class
Let ..= index: index is for the collection

NgNonBindable Not to compile or bind a section

Second {{ content }} is not rendered under ngNonBindable section


4.2. Forms in Angular [user input handlers]
4.2.1. • FormControls and FormGroups encapsulate the inputs in our forms and give
us objects to work with them
4.2.1.1. FormControl: single input field.
4.2.1.1.1. Encapsulate: 1) field’s value 2)states: valid, dirty(changed), errors.
4.2.1.1.2. FormControl can be an attribute to a DOM element
4.2.1.2. FormGroup: wrapper interface of a group of FormControls
4.2.1.3. formModule import: enable NgForm directive. NgForm get attached to
all <form> tags in view. NgForm gives 1) a FormGroup named ngForm, 2)
a (ngSubmit) output.
NgForm ngForm refers to the whole form as an
<form #f="ngForm" object as FormGroup type
(ngSubmit)="onSubmit(f.value)" #f assign a local variable f in this view. Pass
class="ui form"> object of form to f. f.value gives form value
(ngSubmit) output observed
ngForm in template creates a new FormGroup
NgModel at <input> label as attribute The label “for” attribute and the input “id”
<label for="skuInput">SKU</label> attribute are to match
<input type="text"
id="skuInput" Attribute: ngModel = “attribute value”.
placeholder="SKU" empty means no value
name="sku" ngModel> 1. a one-way data binding
2. automatically create a FormControl on
Selector for NgForm: this form(parent FormGroup) with the
form:not([ngNoForm]):not([formGroup]),ngForm, name sku (because of the name attribute
[ngForm] on the input tag)
Automatically attached to form that is not 1)
ngNoForm, 2) formGroup 3)ngForm 4)ngForm Set up association between input tag
and FormControl
ngModel creates a FormControls
NgModel vs. ngModel
NgModel: specify class and refer to
object
ngModel: used in DOM/ template html
comes from the selector of the directive

FormBuilder Build reactive forms


.ts controller import { FormBuilder, FormGroup } from '@angular

/forms';

formBuilder.control : create a new


FormControl
formBuilder.group: create a new
FormGroup
.html template/view
Since myForm is already created as
FormBuilder in constructor, use
[formGroup] and [formControl] to take
value from input myForm
When there is an existing formBuilder
instance created in .ts, in template html,
formGroup and formControl automatically
refer to the formBuilder. However, when
ngForm is used, another new formGroup is
created.
// camel casing in template view

4.2.2. • Validators give us the ability to validate inputs, any way we’d like
4.2.2.1. Assign validator to the FormControl object
4.2.2.2. Check status of the validator in the view and take action
1. Create instance
variable of type
abstractcontrol
2. Assign value to
the instance from
formControls input
3. FormControl/
AbstractControl
syntax:
‘formControl-
name’: [‘value’,
state]
Property ‘sku’ is of
type
AbstractControl
and can be
validated by
method

Use
form.controls[‘sku’]
to call sku without
creating sku
instance

“Required” validation and custom validation

Input formControl, if formControl.value is blank or null, then return


“required” and keep the boolean value true

Input formControl, if formControl.value does not match regexp /^123/,


then return error message “invalidSKU” and keep boolean value true.
Assign multiple/single validators to formControl
Use validators.compose to wrap multiple validators

Use formControl.hasError(‘error key message’) to ngIf division

4.2.3. • Observers let us watch our form for changes and respond accordingly
To watch for changes on a control :
1. get access to the EventEmitter by calling control.valueChanges. then
2. add an observer using the .subscribe method

this.sku.valueChanges.subscribe( Observe value change


(value: string) => { using .subscribe to
console.log('sku changed to:', value); formControls
}
);

4.2.4. NgModel
4.2.4.1. Binds a model to a form. Implements two-way data-binding
[(ngModel)]
[] for input, () for output
Indicates two-way
binding

4.2.4.2.

You might also like