Angular2 . Quick ref notes | part 1

Component overview

Raffaele Abramini
4 min readSep 29, 2017

So I started learning Angular4! It looks like an interesting journey: I’m having the chance to see how another dev team solves the typical issues that a js framework faces.

I listed here the first part of my learnings. You can use this a quick reference guide.

Components

Components are the most basic element of the apps. These are the Lego bricks what will compose your engine. These elements will contain their own JS logic, html structure and styles.

To create a component you can either run this command in the console:

ng generate component componentName

Or this, with a more compact syntax:

ng g c componentName

Or create follow this steps to create a component manually:

1. Create the main .ts file

Create a componentName/componentName.component.ts file. In here, simply define the class that is going to give shape to your component and export it.

export class ComponentNameComponent {
constructor(){}
}

Also, remember to set this class up with the boilerplate structure of a component with a decorator. Import the decorator function from angular and define the minimal settings, selector and templateUrl (or template).

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


@Component({
selector: 'app-component-name',
templateUrl: './header.component.html'
})
export class ComponentNameComponent {
constructor() {}

}
  • selector defines the way you can invoke this component in your app. It can be an HTML selector (default), an attribute or event a class.
  • templateUrl define the path to the html template of the component.
  • or template allows you to define an inline html template (useful for small components)

There are a lot of other properties you can define from here. They are listed here.

2. Create the html template file.

If you specified the templateUrl property, you’ll need also to add this template file.

3. Include component in the app module

In the app.module.ts file, import your newly created component with an import statement and add it in the declarations array of you app module.

import { ComponentNameComponent } from './header/header.component';

@NgModule({
declarations: [
AppComponent,
ComponentNameComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Decorators

Template syntax

Property binding in templates with [ ]. You can edit all the js properties of the DOM element.

[disabled]=“isDisabled”

Event binding in templates with (). Ie

(click)=“myEvent()”;

Standard directives as two ways data binding* using ngModel directive on an input.

[(ngModel)]=“propName
  • For 2 ways Data Binding, FormsModule should be included in the app module.

Structural directives requires * in the syntax. It handles the structure of the DOM element, not only properties. For instance:

<div *ngIf="isVisible"></div>

Local reference #

Directives

Directives are instructions in the DOM. Usually the selector is an attribute. Defined with the @Directive decorator.

If/else conditionals

To use a simple if statement use

*ngIf=”condition”

To use the else in the conditional we need to create a local reference with #, add an ng-template with that reference and enhance the ngIf condition with it. For instance:

<p *ngIf=”isDefined; else #notDefined”>It's defined!</p><ng-template #notDefined>
<p>Not defined</p>
<ng-template>

Conditional style

Use [ngStyle] equal to an object of styles to customise the style of an element. For instance:

<div [ngStyle]="{backgroundColor: getBgColor()}">

NB. The kebab-case of the css props becomes camelCase.

Conditional classes

Use [ngClass] to conditionally set classes

<div [ngClass]="{isActive: isActive()}">

For each loops

Use the structural directive ngFor.

<div *ngFor="let item of items">

You can access the index prop in this fashion:

<div *ngFor="let item of items; let i of index">

Typekit

Variables type restriction

Typescript gives you the possibility of enforcing the type of the variables. Something similar to what you can (and should) do with propTypes in React.

First things first, when you create a class, you have to initialise the properties you are going to use later on. For instance:

class MyClass {
public title: string;
public id: number;

constructor() { }
}

Define variable type on declaration using : . For instance

myStringVar: string = ‘Text text’

To define a variable as array of something, in this case an array of strings:

myArray: string[] = ['server1', 'server2'];

Define inline variable type with <type>myVar. You may want to use brackets.

(<HTMLInputElement>event.target).value

Models

As you know Angular2+ relies on typescript for internal code validation. Therefore, not surprisingly, Angular models are pure TS classes.

A model consists in a TS class where we define the required and possible properties. For instance:

export class MyModel {
public name: string;
public description: string;

constructor(name: string, desc: string) {
this.name = name;
this.description = desc;
}
}

This is as more compact syntax:

export class MyModel {
constructor(public name: string, public description: string) {}
}

This code will allow us to generate valid Recipes with typescript. To do this, just import the model and use to validate objects:

import { MyModel } from "../myModel.model";[...]
export class RecipeListComponent implements OnInit {
recipes: MyModel[] = [];

This article is part of my journey in learning Angular4. Here’s the other articles:

--

--

Raffaele Abramini

Frontend Engineer & Javascript Enthusiast • London, UK