A Look Into Angular

4 minAngular

I have never really worked that much with Angular. I have worked with AngularJS back in the days and worked superficially with the later versions of Angular. This is my notes for looking into the magical world of Angular ✨

Components

The components will often consist of four different elements. This could be the .component.html, .component.css, .component.spec.ts and .component.ts. The component file .component.ts will consist of a decorator and the component class. The decorator is a function with an object that contain configuration settings for the component.

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

// Decorator
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'Hello';
}
js

We can use ng generate component nav to generate components.

export class NavComponent implements OnInit {
  constructor() { }
  ngOnInit() { }
}
js

To call a component we can say <app-nav></app-nav>.

Templates

The templates can be located outside of the .component.ts file in .nav.component.html.

<header>
  <nav>
    <ul>
      <li><a routerLink="/">Home</a></li>
      <li><a routerLink="/about">About</a></li>
    </ul>
  </nav>
</header>
html
<span>{{ appTitle }}</span>
html

Directives are classes that add additional behaviour to elements.

<li *ngFor="let apple of apples"></li>
html

Routing

import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'about', component: AboutComponent },
];
js

Event, Class and Style Binding

One of the most used forms of event binding is the click event. Instead of using [class.big] and [style.color] there is also ngClass() and ngStyle() that works the same way.

<button (click)="click()">Click</button>

<h1 [class.big]="isClicked">Home</h1>
<h2 [style.color]="isClicked ? 'pink': 'black'">Home</h1>
html
export class NavComponent {
  isClicked: boolean = false;

  click() {
    this.isClicked= true;
  }
}
js
.big{
    font-size: 2rem;
}
css

Services

We can use ng generate service click to generate a service. We can then import the ClickService and use dependency injection in the constructor(). Then we can call the method with this.data.click().

export class ClickService {
  click() {
    return console.log('clicked');
  }
}
js
import { Component } from '@angular/core';
import { DataService } from '../data.service';

export class NavComponent {
  constructor(private data: DataService) { }

  click() {
    this.data.click();
  }
}
js

HTTP Client

Angular has its own HTTP library. I am in this example using the library in UserService. Here I am using dependency injection in the constructor() and then using this.http.get('').

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})

export class UserService {
  constructor(private http: HttpClient) { }

  getUsers() {
    return this.http.get('')
  }
}
js

We are then again using dependency injection in the constructor() and then subscribing the data to the users object.

export class HomeComponent implements OnInit {
  users: Object;

  constructor(private data: UserService) { }

  ngOnInit() {
    this.data.getUsers().subscribe(data => {
        this.users = data
      });
  }
}
js

We can then display the data in the template.

<ul *ngIf="users">
  <li *ngFor="let user of users.data">
    <p>{{ user.name }}</p>
  </li>
</ul>
html

Forms

This is mostly from a tutorial

Angular also has its own library for dealing with forms. We first import the FormBuilder, FormGroup and Validators and set the submitted and success properties to false. Then on the lifecycle hook we use the injected formBuilder to set the required form group fields using Validators. On the onSubmit function we set the boolean properties and check if the messageForm is invalid.

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

export class ContactComponent implements OnInit {
  messageForm: FormGroup;
  submitted = false;
  success = false;

  constructor(private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.messageForm = this.formBuilder.group({
      name: ['', Validators.required],
      message: ['', Validators.required]
    });
  }

  onSubmit() {
    this.submitted = true;

    if (this.messageForm.invalid) {
        return;
    }

    this.success = true;
    }
}
js

We can then in the template use the previous settings to set up the validation.

<form [formGroup]="messageForm" (ngSubmit)="onSubmit()">
    <h5 *ngIf="success">Your form is valid</h5>

    <label>
      Name:
      <input type="text" formControlName="name">
      <div *ngIf="submitted && messageForm.controls.name.errors">
        <div *ngIf="messageForm.controls.name.errors.required">Your name is required</div>
      </div>
    </label>
  
    <label>
      Message:
      <textarea formControlName="message"></textarea>
      <div *ngIf="submitted && messageForm.controls.message.errors">
        <div *ngIf="messageForm.controls.message.errors.required">A message is required</div>
      </div>
    </label>

    <input type="submit" value="Send message">
</form>
html