0

I have an angular2 component using Material Design Lite but the checkbox (probably others too) elements are not properly rendered at the first load of the component, while if I interact with the checkboxes, the mdl style is correctly applied. In my component I have

ngAfterViewInit() {
    componentHandler.upgradeDom();
}

but this does not fix my issue, so I used a setTimeout to be executed just after the service has returned some data. This seems to work but is it recommended to do it like that?

this.service.getDetails(this.id)
            .finally(() => {
                setTimeout(() => {
                    componentHandler.upgradeDom();
                }, 10);
            })
            .subscribe((details) => {
                this.details = details;
            });
koninos
  • 4,969
  • 5
  • 28
  • 47
  • It is there, so it can be used. Its just where you want to use and how! – Smit Mar 02 '17 at 11:58
  • May be you can try `changeDetection: ChangeDetectionStrategy.OnPush`.You may find some useful info in [Change Detection Explained](https://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html) – Lini Susan V Mar 02 '17 at 12:13

2 Answers2

1

It would help if you add your component setup to the question as well. Have a look at the Component Styles section of the angular.io docs. I guess all you need is to add the selector and style to the annotation of your component. From the docs:

@Component({
   selector: 'hero-app',
   template: `
       <h1>Tour of Heroes</h1>
       <hero-app-main [hero]=hero></hero-app-main>`,
   styles: ['h1 { font-weight: normal; }']
})
export class HeroAppComponent {
    /* . . . */
}
Stanley85
  • 389
  • 1
  • 5
  • 7
0

Without knowing the ins and outs of your code, purely from a theoretical level your introducing a race condition where (what ever it is that is causing the delay) must finish within 10ms.

Can you confirm that it will always do so? If you can (with 100% certainty) I'd say it's fine. However, from experience I'd say veer away from timeouts and instead use events if possible.

Just a note: I've not used Angular 2 yet but I know that in Angular 1 the digest sometimes needs to be triggered manually. This may be what's going on here.

phayton
  • 146
  • 6