[go: up one dir, main page]

0% found this document useful (0 votes)
0 views21 pages

Angular12guide

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 21

What is Angular?

https://angular.io/start
Angular is a development platform, built on TypeScript. Angular includes:

 A component-based framework for building scalable web applications.


 A collection of well-integrated libraries that cover a wide variety of
features, including routing, forms management, client-server
communication, and more.
 A suite of developer tools to help you develop, build, test, and update
your code.

Components

 Components are the building blocks that compose an application.


 A component includes a TypeScript class with
a @Component() decorator, an HTML template, and styles.
 The @Component() decorator specifies the following:

 A CSS selector that defines how the component is used in a template.


HTML elements in your template that match this selector become
instances of the component.

 An HTML template that instructs Angular how to render the


component.
 An optional set of CSS styles that define the appearance of the
template's HTML elements.

The following is a minimal Angular component.

import { Component } from '@angular/core';

@Component({

selector: 'hello-world',

template: `

<h2>Hello World</h2>
<p>This is my first component!</p>

})

export class HelloWorldComponent {

// The code in this class drives the component's behavior.

To use this component, you write the following in a template:

<hello-world></hello-world>

When Angular renders this component, the resulting DOM looks like this:

<hello-world>

<h2>Hello World</h2>

<p>This is my first component!</p>

</hello-world>

Angular's component model offers strong encapsulation and an intuitive


application structure.

Components also make your application painless to unit test and can
improve the overall readability of your code.

Templates
Every component has an HTML template that declares how that component
renders. You define this template either inline or by file path.

Angular extends HTML with additional syntax that lets you insert dynamic
values from your component.

Angular automatically updates the rendered DOM when your component’s


state changes. One application of this feature is inserting dynamic text:

<p>{{ message }}</p>

The value for message comes from the component class:

import { Component } from '@angular/core';


@Component ({

selector: 'hello-world-interpolation',

templateUrl: './hello-world-interpolation.component.html'

})

export class HelloWorldInterpolationComponent {

message = 'Hello, World!';

When the application loads the component and its template, the user sees
the following:
<p>Hello, World!</p>

Notice the use of double curly braces--they instruct Angular to interpolate


the contents within them.

Angular also supports property bindings, to help you set values for properties
and attributes of HTML elements and pass values to your application's
presentation logic.

<p [id]="sayHelloId" [style.color]="fontColor">

You can set my color in the component!

</p>

Notice the use of the square brackets--that syntax indicates that you're
binding the property or attribute to a value in the component class.

Declare event listeners to listen for and respond to user actions such as
keystrokes, mouse movements, clicks, and touches. You declare an event
listener by specifying the event name in parentheses:

<button

type="button"

[disabled]="canClick"

(click)="sayMessage()">

Trigger alert message


</button>

The preceding example calls a method, which is defined in the component


class:

sayMessage() {

alert(this.message);

The following is a combined example of Interpolation, Property Binding and


Event Binding within an Angular template:

hello-world-bindings.component.ts
hello-world-bindings.component.html

1. import { Component } from '@angular/core';


2.
3. @Component ({
4. selector: 'hello-world-bindings',
5. templateUrl: './hello-world-bindings.component.html'
6. })
7. export class HelloWorldBindingsComponent {
8. fontColor = 'blue';
9. sayHelloId = 1;
10. canClick = false;
11. message = 'Hello, World';
12.
13. sayMessage() {
14. alert(this.message);
15. }
16.
17. }

Add additional functionality to your templates through the use of directives.

The most popular directives in Angular are *ngIf and *ngFor.

Use directives to perform a variety of tasks, such as dynamically modifying


the DOM structure. And create your own custom directives to create great
user experiences.

The following code is an example of the *ngIf directive.

hello-world-ngif.component.ts
hello-world-ngif.component.html

1. import { Component } from '@angular/core';


2.
3. @Component({
4. selector: 'hello-world-ngif',
5. templateUrl: './hello-world-ngif.component.html'
6. })
7. export class HelloWorldNgIfComponent {
8. message = "I'm read only!";
9. canEdit = false;
10.
11. onEditClick() {
12. this.canEdit = !this.canEdit;
13. if (this.canEdit) {
14. this.message = 'You can edit me!';
15. } else {
16. this.message = "I'm read only!";
17. }
18. }
19. }

Angular's declarative templates let you cleanly separate your application's


logic from its presentation.

Templates are based on standard HTML, for ease in building, maintaining, and
updating.

Dependency injection
Dependency injection lets you declare the dependencies of your TypeScript
classes without taking care of their instantiation.

Instead, Angular handles the instantiation for you.

This design pattern lets you write more testable and flexible code.

Even though understanding dependency injection is not critical to start using


Angular, we strongly recommend it as a best practice and many aspects of
Angular take advantage of it to some degree.

To illustrate how dependency injection works, consider the following


example.

The first file, logger.service.ts, defines a Logger class. This class contains
a writeCount function that logs a number to the console.

import { Injectable } from '@angular/core';

@Injectable({providedIn: 'root'})

export class Logger {


writeCount(count: number) {

console.warn(count);

Next, the hello-world-di.component.ts file defines an Angular component.

This component contains a button that uses the writeCount function of the
Logger class.

To access that function, the Logger service is injected into


the HelloWorldDI class by adding private logger: Logger to the constructor.

import { Component } from '@angular/core';

import { Logger } from '../logger.service';

@Component({

selector: 'hello-world-di',

templateUrl: './hello-world-di.component.html'

})

export class HelloWorldDependencyInjectionComponent {

count = 0;

constructor(private logger: Logger) { }

onLogMe() {

this.logger.writeCount(this.count);

this.count++;

Angular CLI

The Angular CLI is the fastest, straightforward, and recommended way to


develop Angular applications.
The Angular CLI makes a number of tasks trouble-free. Here are some
examples:

ng build Compiles an Angular app into an output directory.

ng serve Builds and serves your application, rebuilding on file


changes.

ng Generates or modifies files based on a schematic.


generate

ng test Runs unit tests on a given project.

ng e2e Builds and serves an Angular application, then runs end-to-


end tests.

You'll find the Angular CLI a valuable tool for building out your applications.

First-party libraries

Some of the libraries available to you include:

Angular Advanced client-side navigation and routing based on


Router Angular components. Supports lazy-loading, nested routes,
custom path matching, and more.

Angular Uniform system for form participation and validation.


Forms

Angular Robust HTTP client that can power more advanced client-
HttpClient server communication.

Angular Rich system for driving animations based on application


Animations state.

Angular Tools for building Progressive Web Applications (PWAs)


PWA including a service worker and Web app manifest.

Angular Automated scaffolding, refactoring, and update tools that


Schematics simplify development at large scale.

These libraries expand your application's functionality while also letting you
focus more on the features that make your application unique.

https://stackblitz.com/edit/angular-ivy-cwrbr4

npm install & turbo start


ng serve

Components define areas of responsibility in the UI that let you reuse sets of
UI functionality.

A component consists of three things:

 A component class that handles data and functionality.


 An HTML template that determines the UI.
 Component-specific styles that define the look and feel.

This guide demonstrates building an application with the following


components.

 <app-root>—the first component to load and the container for the


other components.
 <app-top-bar>—the store name and checkout button.
 <app-product-list>—the product list.
 <app-product-alerts>—a component that contains the application's
alerts.
https://stackblitz.com/edit/angular-i2qmx8?file=src%2Fapp%2Fproduct-list%2Fproduct-
list.component.ts

Create the product list

In this section, you'll update the application to display a list of products.


You'll use predefined product data from the products.ts file and methods
from the product-list.component.ts file.

This section guides you through editing the HTML, also known as the
template.

1. In the product-list folder, open the template file product-


list.component.html.

2. Add an *ngFor structural directive on a <div>, as follows.


src/app/product-list/product-list.component.html

<h2>Products</h2>

<div *ngFor="let product of products">

</div>

With *ngFor, the <div> repeats for each product in the list.

Structural directives shape or reshape the DOM's structure, by adding,


removing, and manipulating elements.

3. Inside the <div>, add an <h3> and {{ product.name }}.


The {{ product.name }} statement is an example of Angular's
interpolation syntax.

Interpolation {{ }} lets you render the property value as text.


src/app/product-list/product-list.component.html

<h2>Products</h2>

<div *ngFor="let product of products">

<h3>

{{ product.name }}

</h3>

</div>

The preview pane updates to display the name of each product in the
list.
4. To make each product name a link to product details, add
the <a> element around {{ product.name }}.

5. Set the title to be the product's name by using the property


binding [ ] syntax, as follows:
src/app/product-list/product-list.component.html

<h2>Products</h2>

<div *ngFor="let product of products">

<h3>

<a [title]="product.name + ' details'">

{{ product.name }}

</a>

</h3>

</div>

In the preview pane, hover over a product name to see the bound
name property value, which is the product name plus the word
"details". Property binding [ ] lets you use the property value in a
template expression.

6. Add the product descriptions. On a <p> element, use an *ngIf directive


so that Angular only creates the <p> element if the current product has
a description.
src/app/product-list/product-list.component.html

<h2>Products</h2>
<div *ngFor="let product of products">

<h3>

<a [title]="product.name + ' details'">

{{ product.name }}

</a>

</h3>

<p *ngIf="product.description">

Description: {{ product.description }}

</p>

</div>

The application now displays the name and description of each product
in the list. Notice that the final product does not have a description
paragraph. Angular doesn't create the <p> element because the
product's description property is empty.

7. Add a button so users can share a product. Bind the


button's click event to the share() method in product-
list.component.ts. Event binding uses a set of parentheses, ( ),
around the event, as in the (click) event on the <button> element.
src/app/product-list/product-list.component.html

<h2>Products</h2>
<div *ngFor="let product of products">

<h3>

<a [title]="product.name + ' details'">

{{ product.name }}

</a>

</h3>

<p *ngIf="product.description">

Description: {{ product.description }}

</p>

<button type="button" (click)="share()">Share </button>

</div>

Each product now has a Share button.

Clicking the Share button triggers an alert that states, "The product
has been shared!".
Pass data to a child component

Currently, the product list displays the name and description of each
product. The ProductListComponent also defines a products property that
contains imported data for each product from the products array
in products.ts.

The next step is to create a new alert feature that uses product data from
the ProductListComponent. The alert checks the product's price, and, if the
price is greater than $700, displays a Notify Me button that lets users sign up
for notifications when the product goes on sale.

This section walks you through creating a child


component, ProductAlertsComponent that can receive data from its parent
component, ProductListComponent.

1. Click on the plus sign above the current terminal to create a new
terminal to run the command to generate the component.

2. In the new terminal, generate a new component named product-


alerts by running the following command.

ng generate component product-alerts

The generator creates starter files for the three parts of the
component:
o product-alerts.component.ts
o product-alerts.component.html
o product-alerts.component.css
3. Open product-alerts.component.ts.

The @Component() decorator indicates that the following class is a


component.
@Component() also provides metadata about the component, including
its selector, templates, and styles.
src/app/product-alerts/product-alerts.component.ts

import { Component, OnInit } from '@angular/core';

@Component({

selector: 'app-product-alerts',

templateUrl: './product-alerts.component.html',

styleUrls: ['./product-alerts.component.css']

})

export class ProductAlertsComponent implements OnInit {

constructor() { }

ngOnInit() {

Key features in the @Component() are as follows:


o The selector, app-product-alerts, identifies the component. By
convention, Angular component selectors begin with the prefix app-,
followed by the component name.
o The template and style filenames reference the component's HTML and
CSS.
o The @Component() definition also exports the
class, ProductAlertsComponent, which handles functionality for the
component.
4. To set up ProductAlertsComponent to receive product data, first
import Input from @angular/core.
src/app/product-alerts/product-alerts.component.ts

import { Component, OnInit, Input } from '@angular/core';

import { Product } from '../products';

5. In the ProductAlertsComponent class definition, define a property


named product with an @Input() decorator. The @Input() decorator
indicates that the property value passes in from the component's
parent, ProductListComponent.
src/app/product-alerts/product-alerts.component.ts

export class ProductAlertsComponent implements OnInit {

@Input() product!: Product;

constructor() { }

ngOnInit() {

6. Open product-alerts.component.html and replace the placeholder


paragraph with a Notify Me button that appears if the product price is
over $700.
src/app/product-alerts/product-alerts.component.html

<p *ngIf="product && product.price > 700">

<button type="button">Notify Me</button>

</p>

7. The generator automatically added the ProductAlertsComponent to


the AppModule to make it available to other components in the
application.
src/app/app.module.ts

import { ProductAlertsComponent } from


'./product-alerts/product-alerts.component';
@NgModule({

declarations: [

AppComponent,

TopBarComponent,

ProductListComponent,

ProductAlertsComponent,

],

8. Finally, to display ProductAlertsComponent as a child


of ProductListComponent, add the <app-product-alerts> element
to product-list.component.html. Pass the current product as input to
the component using property binding.
src/app/product-list/product-list.component.html

<button type="button" (click)="share()">

Share

</button>

<app-product-alerts

[product]="product">

</app-product-alerts>

The new product alert component takes a product as input from the product
list. With that input, it shows or hides the Notify Me button, based on the
price of the product. The Phone XL price is over $700, so the Notify
Me button appears on that product.
Pass data to a parent component

To make the Notify Me button work, the child component needs to notify and
pass the data to the parent component. The ProductAlertsComponent needs
to emit an event when the user clicks Notify Me and
the ProductListComponent needs to respond to the event.

In new components, the Angular Generator includes an


empty constructor(), the OnInit interface, and the ngOnInit() method.
Since these steps don't use them, the following code examples omit
them for brevity.
1. In product-alerts.component.ts,
import Output and EventEmitter from @angular/core.
src/app/product-alerts/product-alerts.component.ts

import { Component, Input, Output, EventEmitter } from


'@angular/core';

import { Product } from '../products';

2. In the component class, define a property named notify with


an @Output() decorator and an instance of EventEmitter().
Configuring ProductAlertsComponent with an @Output() allows
the ProductAlertsComponent to emit an event when the value of
the notify property changes.
src/app/product-alerts/product-alerts.component.ts

content_copyexport class ProductAlertsComponent {

@Input() product: Product | undefined;

@Output() notify = new EventEmitter();

3. In product-alerts.component.html, update the Notify Me button with


an event binding to call the notify.emit() method.
src/app/product-alerts/product-alerts.component.html

content_copy<p *ngIf="product && product.price > 700">

<button type="button" (click)="notify.emit()">Notify


Me</button>

</p>

4. Define the behavior that happens when the user clicks the button. The
parent, ProductListComponent—not the ProductAlertsComponent—acts
when the child raises the event. In product-list.component.ts, define
an onNotify() method, similar to the share() method.
src/app/product-list/product-list.component.ts

export class ProductListComponent {

products = products;

share() {

window.alert('The product has been shared!');

onNotify() {

window.alert('You will be notified when the product goes


on sale');

5. Update the ProductListComponent to receive data from


the ProductAlertsComponent.
In product-list.component.html, bind <app-product-alerts> to
the onNotify() method of the product list component. <app-product-
alerts> is what displays the Notify Me button.
src/app/product-list/product-list.component.html

<button type="button" (click)="share()">

Share

</button>

<app-product-alerts

[product]="product"

(notify)="onNotify()">

</app-product-alerts>

6. Click the Notify Me button to trigger an alert which reads, "You will be
notified when the product goes on sale".

You might also like