How does Angular 2 change detection work?

Angular creates a change detector object (see ChangeDetectorRef) per component, which tracks the last value of each template binding, such as {{service.a}}. By default, after every asynchronous browser event (such as a response from a server, or a click event, or a timeout event), Angular change detection executes and dirty checks every binding using those … Read more

Proper way to declare JSON object in Typescript

Here is an easy and naive implementation of what you’re asking for: interface IDataNode { id: number; title: string; node: Array<IDataNode>; } If you want to instantiate said nodes from code: class DataNode implements IDataNode { id: number; title: string; node: Array<IDataNode>; constructor(id: number, title: string, node?: Array<IDataNode>) { this.id = id; this.title = title; … Read more

Why must must ngrx / redux effects return actions? Is using a noop action like elm considered bad practice?

By default, an ngrx/effect dispatches an action. If you want an effect to be ‘fire-and-forget’, all you need to do is add {dispatch: false} as an argument to the @Effects() decorator. From the @ngrx/effects docs: Observables decorated with the @Effect() decorator are expected to be a stream of actions to be dispatched. Pass { dispatch: … Read more

Angular router url returns slash

Instead of trying to use Router (which is not ready to give you final route at this moment of navigation lifecycle), you can use Location service (https://angular.io/api/common/Location) and its method path, which will give you the url without base href. On the contrary, window.location.pathname is not aware of your angular toys and will give you … Read more

Angular2 Get reference to element created in ngFor

If you want to add/remove a class use binding <div *ngFor=”let cookie of cookies” [class.isActive]=”someExpression” ….> or <div *ngFor=”let cookie of cookies” [ngStyle]=”{‘isActive’: someExpression}” ….> Concrete example: activeCookie:string = ‘b’; cookies:string[] = [‘a’, ‘b’, ‘c’]; <div *ngFor=”letcookie of cookies” [class.isActive]=”cookie == activeCookie” ….> If you really want to get a reference you can use <div … Read more

Angular2 Detect if element in template view has class

Add a template variable to be able to query the element. <div #patientDDL class=”overlay-dropdown dropdown” id=”patientDDL”> Query the element @ViewChild(‘patientDDL’) patientDDL:ElementRef; Implement ngDoCheck() to run the check whether the class was added when change detection runs: ngDoCheck() { if(patientDDL.nativeElement.classList.contains(‘open’)) { this.doSomething(); } } or on some specific event @HostListener(‘click’, [‘$event’]) clickHandler(event) { if(patientDDL.nativeElement.classList.contains(‘open’)) { this.doSomething(); … Read more