Angular Cheatsheet

Published on: 2024-03-28

angular

Contents

Directives

Example Directive to apply a css class on click:

dropdown.directive.ts
import { Directive, HostBinding, HostListener } from '@angular/core';

@Directive({
  selector: '[appDropdown]',
})
export class DropdownDirective {
  @HostBinding('class.open') isOpen = false;

  @HostListener('click') toggleOpen() {
    this.isOpen = !this.isOpen;
  }
}

Emitting events

Components can emit their own custom events, so that other components which use it can listen to this custom events, potentially also receiving their passed data.

In the emitting component:

button-click.component.ts
import { Component, EventEmitter, Output } from "@angular/core";

@Component({
  selector: "app-button-click",
  templateUrl: "./button-click.component.html",
  styleUrl: "./button-click.component.css",
})
export class ButtonClickComponent {
  @Output() // makes the custom event usable by other components
  buttonClicked = new EventEmitter<string>();

  onButtonClick() {
    this.buttonClicked.emit("data");
  }
}

The Component using the emitting component:

my-other.component.html
<div class="row">
  <div class="col-xs-10">
    <app-button-click (buttonClicked)="onButtonClicked($event)" />
  </div>
</div>
my-other.component.ts
@Component({
  selector: "my-other.component",
  templateUrl: "./my-other.component.html",
  styleUrl: "./my-other.component.css",
})
export class MyOtherComponent {
  onButtonClcked(data: string) {
    console.log(data);
  }
}

Routing

In Templates

some.component.html
<div class="row">
  <div class="col-xs-10">
    <a
     [routerLink]="['/somepath', 123, 'update']"
     [queryParams]="{ showall: true }"
     fragment="foo"
     class="list-group-item"
    >
      Some Link
    </a>
  </div>
</div>

Programatically

my-other.component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-some',
  templateUrl: './some.component.html',
  styleUrls: ['./some.component.css'],
})
export class SomeComponent {
  constructor(private router: Router) { }

  onLinkClicked(id: number) {
    this.router.navigate(
      ['/somewhere', id, 'foo'],
      {queryParams: {showall: true}},
      fragment: 'foo'
    )
  }
}