admin管理员组

文章数量:1278854

I'm trying to write a ponent that could contain different ponents 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-articleponent.css']
})
export class DynamicArticleComponent implements AfterViewInit {

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

    constructor(private ponentFactoryResolver: ComponentFactoryResolver) {}

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

These are other classes used in the code above:

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

export interface DynamicComponent {
    data: any;
}

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

The elements are getting to the ponent 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:

Thanks in advance.

I'm trying to write a ponent that could contain different ponents 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.ponent.css']
})
export class DynamicArticleComponent implements AfterViewInit {

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

    constructor(private ponentFactoryResolver: ComponentFactoryResolver) {}

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

These are other classes used in the code above:

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

export interface DynamicComponent {
    data: any;
}

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

The elements are getting to the ponent 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:

Thanks in advance.

Share Improve this question edited May 1, 2018 at 14:00 Tom Piaggio asked Apr 30, 2018 at 22:39 Tom PiaggioTom Piaggio 6691 gold badge8 silver badges28 bronze badges 1
  • Think about it from a design point of view. Make your list of elements be part of a class that implements an interface. aka Decorator Pattern. – Hayden Commented Apr 30, 2018 at 22:57
Add a ment  | 

1 Answer 1

Reset to default 16

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.ponent.css']
})
export class DynamicArticleComponent implements AfterViewInit {

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

    constructor(private ponentFactoryResolver: ComponentFactoryResolver) {}

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

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

This code totally works. Hopefully I help someone.

本文标签: javascriptAngular Dynamic Components and ExpressionChangedAfterItHasBeenCheckedErrorStack Overflow