10

I'm trying to make a document generation tool in angular and I'm hitting a challenge with how I would allow a user to dynamically create content.

My components I want to create could have arbitrary models and behavior so I don't think I could use a shared component.

The components I'm describing would not exist at compile time.

I see some documentation for rendering dynamic components. However it mentions that you must list the "dynamic" component in entryComponents in the ngModule. which will not work for my scenario.

Is there another mechanism to get this effect?

2 Answers 2

17

You can create a module and a component on-the-fly, apply decorators to it and then compile it all. Then you will be able to access the compiled components:

@ViewChild('vc', {read: ViewContainerRef}) vc: ViewContainerRef;

constructor(private _compiler: Compiler,
            private _injector: Injector,
            private _m: NgModuleRef<any>) {
}

ngAfterViewInit() {
  const template = '<span>generated on the fly: {{name}}</span>';

  const tmpCmp = Component({template: template})(class {
  });
  const tmpModule = NgModule({declarations: [tmpCmp]})(class {
  });

  this._compiler.compileModuleAndAllComponentsAsync(tmpModule)
    .then((factories) => {
      const f = factories.componentFactories[0];
      const cmpRef = f.create(this._injector, [], null, this._m);
      cmpRef.instance.name = 'dynamic';
      this.vc.insert(cmpRef.hostView);
    })
}

For this approach to work you need to bring compiler to the runtime. For more details on dynamic components read the article:

Sign up to request clarification or add additional context in comments.

9 Comments

Hi. Thanks for the info. Do you happen to know how will this change for angular 8/ivy ? I beliave you now can have both AOT for your core and JIT for code generated on the fly
@user5328504, it's still unclear. We need to wait a little for this information until Ivy is released
In Angular8 I do get the error message "Error: Runtime Compiler not loaded", when calling compileModuleAndAllComponentsAsync in your code. Any clue?
@MaxKoretskyi, now Ivy is here, is it possible to give a direction on the question of @user5328504?
@U.P, haven't explored that yet, I will at some point
|
2

I find out solution that works with Angular 13, and want to share with you.

const importedFile = await import('pathToModule');
const module: NgModuleRef<E> = createNgModuleRef<E>(importedFile[moduleClassName], this._injector);
this.containerRef.createComponent(importedFile[componentClassName], { ngModuleRef: module });

In Angular 13 the Compiler is depracated. The entire compilation process is done under the hood, even if we dynamically import some module/component.

My solution require add an export with component we want to create in the imported module file.

export * from './containers/container.component';

**Instead of importing file you can create component and modules on the fly (like example above) but instead of compiler use just createNgModuleRef and createComponent functions **

2 Comments

Piotr, this is very interesting, can you expand on how to dynamically create component from a template string?
While creating component on fly, can implements "OnInit, AfterViewInit" be added?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.