ng-basics

Angular Basics


Motivation

  • State Change ⟹ UI Change
  • Viel js
  • Viel overhead
  • js 😕

Frameworks


Konfiguration

package.json
Scripts, dependencies
tsconfig.json
TypeScript-Compiler
angular.json
Angular
app.config.ts
App

In den Übungen ✅


index.html

<!doctype html>
<html lang='en'>
<head>
    ...
</head>
<body>
  <app-root></app-root>
</body>
</html>

+ *.ts $\rightarrow$ Compiler $\rightarrow$

<body>
    <app-root></app-root>
    <script src='some.js' type='module'>__SCRIPT_END__
    <script src='main.js' type='module'>__SCRIPT_END__
</body>

app-root

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent {
    // code goes here
}

String Interpolation

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent {
    displayedVariable = signal(42);
    valueJustForTs = 'ok';
}
<p> {{ displayedVariable() }} </p>    ==> <p>42</p>
this.displayedVariable.set(3)         ==> <p>3</p>

Event Binding

<button (click)='foo()'></button>
@Component({ ... })
export class AppComponent {
  n = signal(42);
  
  foo() {
    if (this.n() < 100)
      this.n.set(this.n() + 1);
    else
      this.n.update(value => value - 1)
    console.log(this.n())
  }
}

Events

(click)='foo()'
(dblclick)='foo()'
(focus)='foo()'
(blur)='foo()'
(keydown.enter)='foo()'
(mouseenter)='foo($event)'
(keydown)='foo($event)'

$event enthält Informationen über das Event

  • Welche Taste
  • Input
  • Maustaste
  • Koordinaten
  • ...

Property Binding

url = signal('some-url');
<img src='url()'>
<img src='{{ url() }}'>
<img [src]='url()'>
  • property vs [property] 🤔
  • Intellisense 👍

Styling

<p [class.hidden]='error()'>Error!</p>
if error():
  give the <hidden> class
<p [style.display]='error() ? "none" : "block"'>Error!</p>

mehrere

<p [ngClass]='{"hidden": error(), "huge": aria()}'>Error!</p>
if error():
  give the <hidden> class
if aria():
  give the <huge> class

Two-Way-Binding

age = signal(16);
<input [(ngModel)]='age' >

keine (), wir wollen nicht nur den Wert


Cheat Sheet

{{ interpolation() }}
<button (click)='action($event)' >Event Binding</button>
<a [href]='url()' >Property Binding</a>
<input [(ngModel)]='twoWay' >