Tom Piaggio
Tom Piaggio

Reputation: 669

Angular Dynamic Components and ExpressionChangedAfterItHasBeenCheckedError

I'm trying to write a component that could contain different components dynamically. My goal is to be able to write an article where I could either write a paragraph or add a tweet.

This is the code for DynamicArticleComponent:

@Directive({
  selector: '[dynamic-query]'
})
export class QueryDirective {
  constructor(public viewContainerRef: ViewContainerRef) {}
}

@Component({
  selector: 'app-dynamic-article',
  template: 
  `<ng-container *ngFor="let element of elements">
      <ng-template dynamic-query></ng-template>
  </ng-container>`,
  styleUrls: ['dynamic-article.component.css']
})
export class DynamicArticleComponent implements AfterViewInit {

    @Input() elements: Element[];
    @ViewChildren(QueryDirective) queryDirectives;

    constructor(private componentFactoryResolver: ComponentFactoryResolver) {}

    ngAfterViewInit() {
      this.queryDirectives.forEach((queryDirective: QueryDirective, index) => {
        const element = this.elements[index];
        const componentFactory = this.componentFactoryResolver.resolveComponentFactory(element.component);
        const containerRef = queryDirective.viewContainerRef;
        containerRef.clear();
        const newComponent = containerRef.createComponent(componentFactory);
        (<DynamicComponent>newComponent.instance).data = element.data; 
      });
    }
}

These are other classes used in the code above:

export class Element {
    constructor(public component: Type<any>, public data) {}
}

export interface DynamicComponent {
    data: any;
}

I'm having trouble rendering the <ng-templates>. It just renders comments and it doesn't change after the view loads. This is what's rendered: enter image description here

The elements are getting to the component correctly. My idea is to render all the templates, then get them with the ViewChildren decorator, and render the elements where they are supposed to be. Is there other solution to this problem?

Also, this is how the elements reach the DynamicArticleComponent:

enter image description here

Thanks in advance.

Upvotes: 1

Views: 2294

Answers (1)

Tom Piaggio
Tom Piaggio

Reputation: 669

Ok, there were two main problems with my code. The first one was pretty dumb. I didn't add the directive to the app module declarations, so it was just like any other html property; angular just didn't expect it, so it didn't look for it. However, after adding it to the app module, it threw ExpressionChangedAfterItHasBeenCheckedError. This error is caused because I'm changing variables after the view has load. For a more in depth explanation look this blog post.

In summary, what I did was extracting what I was doing inside the ngAfterViewInit into its own function and calling it from a promise. What this does, is creates a microtask queued after the syncronous code has fininshed executing. To learn more about micro and macro tasks in angular, look at this post: I reverse-engineered Zones (zone.js) and here is what I’ve found.

Here is how the code ended up:

@Directive({
  selector: '[dynamic-query]'
})
export class QueryDirective {
  constructor(public viewContainerRef: ViewContainerRef) {}
}

@Component({
  selector: 'app-dynamic-article',
  template: 
  `<ng-container *ngFor="let element of elements">
    <ng-template dynamic-query></ng-template>
  </ng-container>`,
  styleUrls: ['dynamic-article.component.css']
})
export class DynamicArticleComponent implements AfterViewInit {

    @Input() elements: Element[];
    @ViewChildren(QueryDirective) queryDirectives;

    constructor(private componentFactoryResolver: ComponentFactoryResolver) {}

    ngAfterViewInit() {
        Promise.resolve(null).then(() => this.renderChildren());
    }

    private renderChildren() {
      this.queryDirectives.forEach((queryDirective: QueryDirective, index) => {
        const element = this.elements[index];
        const componentFactory = this.componentFactoryResolver.resolveComponentFactory(element.component);
        const containerRef = queryDirective.viewContainerRef;
        containerRef.clear();
        const newComponent = containerRef.createComponent(componentFactory);
        (<DynamicComponent>newComponent.instance).data = element.data; 
      });
    }
}

This code totally works. Hopefully I help someone.

Upvotes: 16

Related Questions