Angular cheatsheet

Enum dans un Template

Pour utilisation d'une enum dans un template, il faut ajouter le code suivant dans le composant :

1public readonly myEnum : typeof MyEnum = MyEnum;

Apres on peut l'utiliser dans le template MyEnum.VALUE1

Communication parent/enfant

Le parent appel l'enfant : Parent.component.ts :

1import {Subject} from 'rxjs/Subject';
2...
3export class ParentComp {
4  changingValue: Subject<boolean> = new Subject();
5        
6  tellChild() {
7    this.changingValue.next(true);
8  }
9}

Parent.component.html

1<my-comp [changing]="changingValue"></my-comp>

Child.component.ts

 1...
 2export class ChildComp implements OnInit{
 3  @Input() changing: Subject<boolean>;
 4  
 5  ngOnInit(){
 6    this.changing.subscribe(v => { 
 7      console.log('value is changing', v);
 8    });
 9  }
10}

Fermer un observable

Pour fermer un observable de façon automatique

 1@Component({...})
 2export class AppComponent implements OnInit, OnDestroy {
 3    over$ = new Subject();
 4    
 5    ngOnInit () {
 6        var observable$ = Rx.Observable.interval(1000);
 7        observable$
 8          .pipe(takeUntil(this.over$))
 9          .subscribe(x => console.log(x));
10    }    
11    
12    ngOnDestroy() {
13        this.over$.next();
14        this.over$.complete();
15    }
16}

Pour d'autres façon de le faire, voir ici : StackOverflow