Angular

Components

What is the component?

Components are a logical piece of code for Angular application. 

What is the component?

It consists of the following:

  • Template − This is used to render the view for the application. This contains the HTML that needs to be rendered in the application. This part also includes the binding and directives.
  • Class − Contains properties and methods. This has the code which is used to support the view.
  • Metadata − This has the extra data defined for the Angular class. It is defined with a decorator.

What is the component?

<Template>

Class {}

@Metadata

Menu

Header

Footer

Feed

Post

Application layout

Components tree

App

Menu

Feed

Header

Footer

Post

Components implementation

Getting started

$ ng g component components/feed
@NgModule({
  declarations: [
    AppComponent,
    --> FeedComponent,
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
import { Component } from '@angular/core';

@Component({
  selector: 'app-feed',
  templateUrl: './feed.component.html',
  styleUrls: ['./feed.component.css']
})
export class FeedComponent {

}

Demo

Feed example

import { Component } from '@angular/core';
import { Post } from '../models/post.ts';

@Component({
  selector: 'app-feed',
  templateUrl: './feed.component.html',
  styleUrls: ['./feed.component.css']
})
export class FeedComponent {
  posts = [
    {
      id: 1,
      title: 'Breaking news!',
      text: 'Voluptate labore veniam sit exercitation nisi fugiat voluptate laboris',
      likes: 2
    },
    {
      id: 2,
      title: 'Meows news!',
      text: 'Laborum minim sit incididunt exercitation laborum commodo laborum.',
      likes: 42
    }
  ];

  likePost(likedPost: Post) {
    const postIdx = this.posts.findIndex((post) => post.id === likedPost.id);
    this.posts[postIdx].likes++;
  }
}
<div class="post" *ngFor="let post of posts">
  <h1>{{ post.title }}</h1>
  <p>{{ post.text }}</p>
  <button (click)="likePost(post)">Like!</button>
</div>
export interface Post {
  id: number;
  title: string;
  text: string;
  likes: number;
}

Demo

Components interaction

Bindings

  • Property binding
  • Event binding
  • Two-way binding

<Template>

Class {}

[property] @Input

(event)

@Output

[ property binding ]

( event binding )

[( two-way binding )]

Bindings in action

<app-post
    *ngFor="let post of posts"
    [post]="post"
    (like)="likePost($event)">
</app-post>
<input [(ngModel)]="yourName" name="yourName">
<h1>Hello {{ yourName }}!</h1>
<h1 *ngIf="yourName">
    Hello {{ yourName }}!
</h1>

Demo

Smart and Presentational Components

Smart Component

Service 1

Smart Component

Service 2

  • Connected to services
  • Knows how to load data and how to react to data changes
  • Manages state
  • Focuses on how things work

Presentational (aka Dump) Component

Smart Component

  • Fully defined by their bindings (can be reused)
  • Stateless (no logic inside)
  • Focuses on how things look

Presentational Component

@Input() …

@Output() …

Presentational Component

@Input() …

@Output() …

Lifecycle Hooks

Lifecycle Hooks

  • ngOnChanges()
  • ngOnInit()
  • ngDoCheck()
  • ngAfterContentInit()
  • ngAfterContentChecked()
  • ngAfterViewInit()
  • ngAfterViewChecked()
  • ngOnDestroy()

Respond when Angular (re)sets data-bound input properties. The method receives a SimpleChanges object of current and previous property values.

 

Called before ngOnInit() and whenever one or more data-bound input properties change.

Initialize the directive/component after Angular first displays the data-bound properties and sets the directive/component's input properties.

 

Called once, after the first ngOnChanges().

Detect and act upon changes that Angular can't or won't detect on its own.

 

Called during every change detection run, immediately after ngOnChanges() and ngOnInit().

Respond after Angular projects external content into the component's view / the view that a directive is in.

 

Called once after the first ngDoCheck().

Respond after Angular checks the content projected into the directive/component.

 

Called after the ngAfterContentInit() and every subsequent ngDoCheck().

Respond after Angular initializes the component's views and child views / the view that a directive is in.

 

Called once after the first ngAfterContentChecked().

Respond after Angular checks the component's views and child views / the view that a directive is in.

 

Called after the ngAfterViewInit() and every subsequent ngAfterContentChecked().

Cleanup just before Angular destroys the directive/component. Unsubscribe Observables and detach event handlers to avoid memory leaks.

 

Called just before Angular destroys the directive/component.

Components Metadata

animations - list of animations of this component

 

changeDetection - change detection strategy used by this component

 

encapsulation - style encapsulation strategy used by this component

 

entryComponents - list of components that are dynamically inserted into the view of this component

 

* exportAs - name under which the component instance is exported in a template

 

* host - map of class property to host element bindings for events, properties and attributes

 

* inputs - list of class property names to data-bind as component inputs

 

Interpolation - custom interpolation markers used in this component's template

 

moduleId - ES/CommonJS module id of the file in which this component is defined

• * outputs - list of class property names that expose output events that others can subscribe to


• * providers - list of providers available to this component and its children


• * queries - configure queries that can be injected into the component


• * selector - css selector that identifies this component in a template


• styleUrls - list of urls to stylesheets to be applied to this
component's view


• styles - inline-defined styles to be applied to this component's view


• template - inline-defined template for the view


• templateUrl - url to an external file containing a template for the view


viewProviders - list of providers available to this component and its view children

 

* - inherited from Directive

Useful links

Q & A

Angular. Components

By Pavel Razuvalau

Angular. Components

  • 1,104