Angular 6 Cheat Sheet

What various Angular Code snippets do.

Onejohi
5 min readSep 6, 2018

--

A cheat sheet is a note of notes for quick reference. You might want to bookmark this page as I have collected some of the various code snippets from Angular docs and try to explain them quickly and easily to quickly help you grip Angular and understanding it better as I myself pride in being an Angular expert… I did a quick IQ test on Pluralsight and found myself slightly below expert level lol. Here’s how I did.

Not so bad for a self-taught developer.

With such proficiency in my first attempt, I decided to help out my fellow Angular enthusiasts into understanding Angular better. Here’s a list of topics I decided to pursue. This article will be part of a two-part series, this will reduce the size of the article to make it less lengthy. A link to the second part will be provided upon completion.

Bootstrapping.

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';platformBrowserDynamic().bootstrapModule(AppModule);

This starts(bootstraps) up the app using the specified module, in this case, being AppModule. The bootstrapped app becomes the root module of the entire Angular application.

NgModules.

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

The ngModule contains metadata that will be injected into the app. These include declarations, imports, exports, providers, bootstrap and schemas.

@ngModule({
declarations: [AppComponent, HeaderComponent],
imports: [BrowserModule, MatToolBarModule],
exports: [MyDatePipe],
providers: [HttpServiceProvider, LocalDataProvider],
bootstrap: [AppModule],
schemas: [NO_ERRORS_SCHEMAS]
})

The declarations define a list of components, pipes, and directives that should be used in the module. The imports define a list of modules to import and these should be accessible by the declarations of the modules they’re being imported to. The exports are components, directives, and pipes that are accessible to modules that import this specific module (app). The providers are services that inject data into the module and implement Dependency Injection. The bootstrap metadata contains components to bootstrap as soon as the AppModule bootstraps. Finally, the schemas are elements and properties that aren’t Angular directives nor components that you would wish to add to the app.

There are two available schemas, NO_ERRORS_SCHEMA which specify any element and properties are allowed and CUSTOM_ELEMENTS_SCHEMA which specify that any custom element (element names with a “-”) with any properties are allowed. Examples of custom schema elements are <mat-toolbar>

Template Syntax.

Here are some of the template syntax for the HTML and an explanation to each.

<input [value]="firstName">

This binds the property value to the result of the expression firstName from the component.

<div [attr.role]="myRole"> </div>

This binds the attribute role to the result of the expression myRole from the component.

<div [class.active]="isActive"> </div>

This binds the CSS class active to the div element depending on if the isActive expression in the component is true or false.

<div [style.width.px]="width"> </div>

This binds the style property width in pixels to the value of the expression width in the component.

<button (click)="doSomething($event)"> Click Me </button>

This calls the method/function doSomething while passing the event object into the function when a click event is triggered on the element.

<p title="My name is {{name}}"> </p>

This binds the text content into an interpolated string. This is similar to [title]=”’My name is’ + name”

<p [(username)]="user" > </p>

This creates a feature of Angular called two-way data binding where when data changes in the component, it’s immediately reflected in the template.

<video #movieplayer>
<button (click)="movieplayer.play()"> Play Movie </button>
</video>

This creates a local variable only accessible to the component movieplayer that gives access to the video element instance in event-binding and data-binding expressions.

<p *unless="expression"> </p>
//equivalent to
<ng-template [unless]="expression"> </ng-template>

The * symbol turns the element into an embedded template.

<p> Date: {{ currentDate | datetime }} </p>

Transforms the value of the expression currentDate from the component using the datetime pipe. This pipe is built-in but you can create custom pipes.

<p> {{user?.username}} </p>

This expression makes the user field optional if undefined by using the safe navigation operator (?), the rest of the expression is ignored as well.

Built-in directives.

Built-in directives are imported from the angular/common module.

import { CommonModule } from '@angular/common';

Let’s go through the four of them.

<section *ngIf="show"> </section>

This creates or hides (completely removes, don’t mistake this with the “hidden” HTML property) the element depending on the show expression value in the component.

<li *ngFor="let user of users"> </li>

This makes the li element a template then uses the contents of the users array to instantiate a view for each item in the list. This is similar to using the forEach function in JS to create a view for each element in an array. The ngFor directive can only be used on arrays or strings.

<div [ngSwitch]="condition">
<div [ngSwitchCase]="case1"> ... </div>
<div [ngSwitchCase]="case2"> ... </div>
</div>

This swaps the content of the div depending on the value of the condition in the expression. The content shifts according to the value specified in the case. This works similar to the Switch attribute in JS.

<div [ngClass]="{'active': isActive }"> </div>

This binds the CSS class active to the element depending on if the isActive expression is true or false.

Class Decorators.

Class decorators are imported from the angular core module as shown below.

import { Directive, ...} from '@angular/core';

Replace Directive with the decorator you would like to use.

@Component({...})
class AppComponent() { }

This declares that the class is a component and also provides metadata about the component.

@Directive({...})
class MyDirective() { }

This declares the class is a directive and provides metadata about it.

@Pipe({...})
class MyPipe() { }

This declares that the class is a pipe and provides metadata about the pipe.

@Injectable()
class MyService() { }

This declares that the class contains dependency injectors, this means the data provided by the injector should be injected into the constructor when creating an instance of this class.

And last on this first part is…

Forms.

import { FormsModule } from '@angular/forms';

This is imported from the angular forms module as shown above and it provides two-way data binding for form elements, data validation, and parsing.

<input [(ngModel)]="firstName">

The rest will be provided in due time. Have patience in me and a million thanks for going through this article. Please leave a few claps if this content proved helpful to you and don’t forget to subscribe. ;)

--

--

Onejohi

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