Angular 6 Cheat Sheet (Part II)

The final segment on various Angular Code snippets and their uses.

Onejohi
7 min readNov 23, 2018

A few weeks ago, I wrote started a two-part series documenting cheat sheet codes for Angular 6. Here is the link to part I.

It is noteworthy to remember this applies majorly from Angular 2 to the current version 7. Much of the code hasn’t changed, just minor updates and patches here and there. This week, we’ll be looking at the following topics.

  • Directive Configuration.
  • Component Configuration.
  • Decorators for directives and components.
  • Change detection and lifecycle hooks.
  • Dependency Injection Configuration.
  • Routing and Navigation.

This article assumes you are comfortable with creating an Angular app and wish to learn more. If you’re not familiar with Angular, please start here.

Let us begin with our first candidate…

Directive Configuration.

A directive is a marker that is attached to a DOM element that lets the Angular HTML compiler ($compile) hook specific behaviors to that DOM Element and even change/transform its children or the element itself. You can define custom directives and attach behaviors to various elements contained in the DOM. The options created provide metadata that dictate how the directive should be processed, instantiated and used at runtime. Here are some options and their descriptions.

selector: '.btn-primary:not(a)'

This specified the CSS selector that identifies the directive in the HTML template.

Note: This does not support parent-child relationship selectors such as .btn > .btn-icon

providers: [MyService, { provide: ... }]

This defines a list of dependency injection providers and their children.

Component Configuration.

The @Component extends @Directive so that the modifications will apply to @Directive as well.

moduleId: module.id

This is set to resolve stylesheets and HTML template URL errors. If this is set, the templateUrl and styleUrl are resolved relative to the component class.

viewProviders: [MyService, { provide: ... }]

This lists dependency injection providers that are limited to the component’s view scope.

template: 'Hello {{name}}!',
templateUrl: 'home-template.html'

The first line of code shows how to use inline templates for the component. This will display Hello name where name is the value of name: String = "" in the component class. The second line of code shows how to include external templates. The HTML code is contained in the document home-template.html which resides in the same folder as the component.

styles: ['.dark-bg { background-color: #333 }']
styleUrls: ['style.component.css','custom-buttons.css']

Similar to the inline templates, the first line shows how to include inline styles to the component while the second line shows how to include external CSS stylesheets using their URLs to style the component template.

To put all this together, a custom component with its options looks something like this.

Decorators for Directives and Components.

These are class field decorators that are imported from "@angular/core"

@Input() username;

This declares an input property that you can change using property binding. This input property is used by child components to accept data from the parent when two components interact.

@Output() isActive = new EventEmitter();

This creates an output property that is bound to a value in the component. This property will fire off events to all subscribed members when an event happens to the template i.e (isActive)="notifyContacts()" and is used by child components to send data to the parent component in form of an event.

@ViewChild(myPredicate) childComponent;
@ViewChildren(myPredicate) myChildComponents;

The first decorator binds the first result of the component view query (myPredicate) to the property childComponent of the class while the second decorator binds the results of all component view query.

@ContentChild(myPredicate) childComponent;
@ContentChildren(myPredicate) childrenComponents;

The first decorator binds the first result of the component content query. Both are used similar to @ViewChild and @ViewChildren , the only difference being the later is used for content while the other is used for views.

@HostListener('click', ['$event'])onClick(e) {...}

This subscribes to a host element click event using the onClick() component method while passing '$event' as an argument.

@HostBinding('class.valid') isValid;

This binds a host element propery that is a CSS class called .valid to a component propery named isValid .

Change Detection and Lifecycle hooks.

These methods detect changes in application state, and the application lifecycle and execute when one of the changes or states are detected to have changed. This means you can perform some tasks during specific instances in your application like on initialization, when the view has been initialized, or when an instance is destroyed.

constructor(ms: MyService) { ... }

The contructor method is called before any other lifecycle hooks and is best used to inject dependencies into the component as shown above where I inject MyService using the alias ms to represent it in this instance where the methods in MyService class are accessible via this.ms.doSomething() .

ngOnChanges(changedItem) { ... }

This method is called after every change to input properties using @Input decorator before processing content or child views.

ngOnInit() { ... } 

This is called after the contructor, initializing input properties and the first call to ngOnChanges() has occured. It’s called when your component has been initialized.

ngOnDestroy() { ... }

This is called once, before the instance of the class is destroyed.

ngDoCheck() { ... }

This method is called every time that input properties are checked. It’s best used to extend change detection by enabling the developer to perform custom checks on their input data/properties.

ngAfterContentInit() { ... }

Called after ngOnInit() when component data has been initialized.

ngAfterContentChecked() { ... }

Called after every time the component content is checked.

ngAfterViewInit() { ... }
ngAfterViewChecked() { ... }

The first method is called after ngAfterContentInit() when component views and child views have been initialized. The second method ngAfterViewChecked() is performed every time the component view or child views that a directive is in are checked.

Dependency Injection Configuration.

This one will be quite simple. There are three ways you can configure dependency injection in your application.

{ provider: MyService, useClass: MyMockService }
{ provider: MyService, useFactory: myFactory }
{ provider: MyValue, useValue: 1995 }

The code above should be written in your app.module.ts while configuring dependencies for your application where you specify the providers. The first line overrides MyService and replaces it with MyMockService instead. The second line overrides MyService and replaces it with a myFactory factory function. The third and last line overrides the provider for MyValue with a hard coded 1995 value which happens to be the year I was born 😜.

Routing and Navigation.

Here’s where things start to get a little interesting. Routes help us navigate our angular app as though we are moving through different web pages. But what really happens is Angular simply switches components on the element<router-outlet> which loads the ‘routes’ (components). All methods and properties of router are derived from '@angular/router' module.

import { Routes, RouterModule } from '@angular/router'...const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'login/:token', component: LoginComponent },
{ path: '/login', component: LoginComponent, data: {
username: 'Tony',
password: 'hfd8a8aff0fad'
} },
{ path: 'oldlink', redirectTo: '/newroute' }
]
const routing = RouterModule.forRoot(routes)

The code above makes use of Routes and RouterModule to configure four routes for the application. The first default routes to HomeComponent , the second route carries a :token parameter in the string URL similar to a GET request, the third route carries JSON data username and password similar to a POST request while the last route simply redirects and old route to a newer one.

<router-outlet></router-outlet>

This mostly goes in your index.html file and marks the location where the active component route will load.

<a routerLink='/path'> </a>
<a [routerLink]='["/path", routeParameters"]'> </a>
<a [routerLink]='["/path"]' [queryParams]="{ userid: 88 }"> </a>
<a [routerLink]='["/path"]' fragment="anchor"> </a>

The three lines of code show how Angular links are accessible to the application.

Note: You cannot use href for Angular routes and navigation.

You can create links to different views based on the route path, optional parameters, query parameters, and a fragment. To navigate to a root route, use / as a prefix, for a child route in root use ./ and for a parent route in root prefix with ../ .

<a [routerLink]='["/hello"]' routerLinkActive='active'> </a>

The classes provided are added to the element when the routerLink is activated or becomes the current active route.

class CanActivateGuard implements CanActivate {
canActivate(route: ActivatedRouteSnapShot, state: RouterStateSnapShot): Observable<boolean> | Promise<boolean> {...}

This interface that implements CanActivate is used for defining a class that the router should call first to determine if it should activate this component, that’s why its result is returned as an observable or promise that resolves to a boolean.

You can then use it in your routes like so,

{ path: '', component: HomeComponent, canActivate: [CanActivateGuard] }

As an extension, you can also use CanDeactivateGuard and implement CanDeactivate<T> to determine if the router should deactivate this component after a navigation. Also, CanActivateChildGuard can be used and implement CanActivateChild to determine if the router should activate the child route. There’s also a ResolveGuard that implements Resolve<T> that defines a class that the router should call first to resolve route data before rendering the route. The final one is CanLoadGuard that implements CanLoad and defines that the router should first check if the lazy loaded module should be loaded.

I truly hope this cheat sheet series will help you understand Angular better and quickly remember how to create the functionalities listed in this article. If you find this cheatsheet useful, bookmark it and share to your peers and friends. Thank you for your time, please follow for more indulging articles. 😉

--

--

Onejohi

Creative 🚀 | Gamer 🎮 | Web & App developer 💻📱 | Graphics Designer 📏📝 | Entrepreneur 💶 | Cool AF 😎🤓 https://onejohi.com | WhatsApp +254727321766