Angular cheatsheet

Angular cheatsheet

Enum dans un Template

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

1
public 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 :

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

Parent.component.html

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

Child.component.ts

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

Fermer un observable

Pour fermer un observable de façon automatique

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

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

Généré avec Hugo
Thème Stack conçu par Jimmy