Aus SatriaWiki
Wechseln zu: Navigation, Suche
K (Finalize)
(Validierungen)
Zeile 29: Zeile 29:
  
 
== Eingabe ==
 
== Eingabe ==
=== Validierungen ===
+
=== Template-driven validation with custom validator ===
{|
+
{| border="1"
|-
+
! componentCode.ts !! componentCode.html
! component.ts !! template.html
 
 
|-
 
|-
 
|
 
|
 
<code><poem><nowiki>
 
<code><poem><nowiki>
import { AbstractControl, FormBuilder, FormGroup, ValidatorFn, Validators } from '@angular/forms';
+
import { FormControl, NG_VALIDATORS, Validator, ValidationErrors } from '@angular/forms';
class
+
 
 +
@Component(...)
 +
export class ...
 
{
 
{
   angForm: FormGroup;
+
   field1String: string;
 +
  otherString: string;
 +
  @ViewChild("formName")
 +
  formName: any;
  
   constructor(private formBuilder: FormBuilder)
+
   update()
 
   {
 
   {
     this.angForm = formBuilder.group({
+
    // Man KANN so etwas hier tun:
      email: ['', Validators.required],
+
     this.formName.controls.field1.updateValueAndValidity();
      special: ['', this.customValidation("DE")]
 
    })
 
 
   }
 
   }
 +
}
  
   customValidation(loc: string) : ValidatorFn
+
@Directive(
 +
  selector: '[customValidator]',
 +
  providers: [{ provide: NG_VALIDATORS, useExisting: CustomValidator, multi: true }]
 +
)
 +
export class CustomValidator
 +
{
 +
   @Input('customValidator')
 +
  param: string;
 +
 
 +
  validate(control: FormControl): ValidationErrors
 
   {
 
   {
     return (control: AbstractControl) =>
+
     // Eine Auswertung, die param verwendet (oder auch nicht)
     {
+
     return { myNamedError: true };
      if (loc == "DE" && control.value == "Deutsch")
 
        return null;
 
      else
 
        return { wrongCountry: true };
 
    }
 
 
   }
 
   }
 
}
 
}
 
</nowiki></poem></code>
 
</nowiki></poem></code>
||
+
|valign="top"|
 
<code><poem><nowiki>
 
<code><poem><nowiki>
<input type="text" formControlName="email" [(ngModel)]="useremail"/>
+
<form #formName="ngForm" novalidate>
<div *ngIf="angForm.controls['email'].invalid && (angForm.controls['email'].dirty || angForm.controls['email'].touched)">
+
  <input #field1="ngModel" type="text" name="field1" [(ngModel)]="field1String" required [customValidation]="otherString"/>
  <div *ngIf="angForm.controls['email'].errors.required">
+
  <div *ngIf="formName.invalid && (formName.dirty || formName.touched)">
    Pflichtfeld!
+
    <div *ngIf="formName.errors.required">
  </div>
+
      Pflichtfeld!
</div>
+
    </div>
 
+
    <div *ngIf="formName.errors.myNamedError">
<input type="text" formControlName="special" [(ngModel)]="custom"/>
+
      Speziellere Fehlermeldung!
<div *ngIf="angForm.controls['special'].invalid && (angForm.controls['special'].dirty || angForm.controls['special'].touched)">
+
    </div>
  <div *ngIf="angForm.controls['special'].errors.wrongCountry">
 
    Falsches Land!
 
 
   </div>
 
   </div>
</div>
+
</form>
 
</nowiki></poem></code>
 
</nowiki></poem></code>
 
|}
 
|}

Version vom 20. März 2020, 14:59 Uhr

UI

Datum formatieren

(new Date()).toLocaleDateString("de-DE", { day: '2-digit', month: '2-digit', year: 'numeric' });

Quellen:

https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

Pipes mit Parametern

Möchte man ineinem Template einen Wert durch eine Pipe schicken und dabei Parameter mitgeben, werden diese ungewöhnlicherweise mit einem Doppelpunkt eingeleitet und getrennt:

{{status | round: 2[: 4]}}

In eckigen Klammern stehen mögliche weitere Paramter.

In der Pipe-Klasse werden diese Parameter in der transform() Methode dann als Array oder einzeln übergeben, je nach dem, wie die Methode deklariert ist:

transform(value: any, arg1?: any, arg2?: any)

oder

transform(value: any, args?: any[])

Eingabe

Template-driven validation with custom validator

componentCode.ts componentCode.html


import { FormControl, NG_VALIDATORS, Validator, ValidationErrors } from '@angular/forms';

@Component(...)
export class ...
{
  field1String: string;
  otherString: string;
  @ViewChild("formName")
  formName: any;

  update()
  {
    // Man KANN so etwas hier tun:
    this.formName.controls.field1.updateValueAndValidity();
  }
}

@Directive(
  selector: '[customValidator]',
  providers: [{ provide: NG_VALIDATORS, useExisting: CustomValidator, multi: true }]
)
export class CustomValidator
{
  @Input('customValidator')
  param: string;

  validate(control: FormControl): ValidationErrors
  {
    // Eine Auswertung, die param verwendet (oder auch nicht)
    return { myNamedError: true };
  }
}


<form #formName="ngForm" novalidate>
  <input #field1="ngModel" type="text" name="field1" [(ngModel)]="field1String" required [customValidation]="otherString"/>
  <div *ngIf="formName.invalid && (formName.dirty || formName.touched)">
    <div *ngIf="formName.errors.required">
      Pflichtfeld!
    </div>
    <div *ngIf="formName.errors.myNamedError">
      Speziellere Fehlermeldung!
    </div>
  </div>
</form>

Observables

One-time subscription

Für rxJS > 5.5:

import { first } from 'rxjs/operators';
observableMethod.pipe(first()).subscribe(method);

Es gibt wohl aber Situationen, in denen die Subscription sowieso automatisch beendet wird...

Finalize

Der operator "finalize" wird ausgeführt nachdem das Observable fertig ist, ob mit oder ohne Fehler:

import { finalize } from 'rxjs/operators';
asyncMethod.pipe(finalize(() => executeThis()));

Migrations

5 to 6

https://update.angular.io/#5.2:6.1l2

Mindestens node 8 muss verwendet werden!

Die globale Angular/CLI auf 6 anheben (6.2.9):

npm install -g @angular/cli@6

Den lokalen Workspace auf Angular/CLI 6 anheben:

ng update @angular/cli@6

Skripte in der package.json anpassen: CLI Kommandos beginnen jetzt immer mit einem Doppelstrich: --prod --aot ...

Angular framework auf 6 anheben:

ng update @angular/core@6

Die letzte Angular 6 Version war 6.1.10

Dazu passen folgende Versionen, die ggf. nicht automatisch angehoben werden (in package.json anpassen):

  • @angular/material@6.4.7
  • rxjs@6.5.4

Die Syntax in rxjs 6 hat sich geändert, und es gibt Migrationstools, die das anpassen:

npm install -g rxjs-tslint
rxjs-5-to-6-migrate -p src/tsconfig.app.json

Danach kann rxjs-compat aus der package.json entfernt werden.

6 to 7

https://update.angular.io/#6.1:7.2l2

Die globale Angular/CLI auf 7 anheben (7.3.9):

npm install -g @angular/cli@7

Den lokalen Workspace auf Angular/CLI 7 anheben:

ng update @angular/cli@7 @angular/core@7

Die letzte Angular 6 Version war 7.2.16

Dazu passen folgende Versionen, die ggf. nicht automatisch angehoben werden (in package.json anpassen):

  • @angular/material@7.3.7
  • @angular/cdk@7.3.7