2

Please, tell how to do the following in Angular2/4 :

Component SomeComponent gets from @Input the following html as a string :

  `<am-input
    [placeholder]="'Placeholder'"
    [disabled]="true">
  </am-input>`

How can SomeComponent create a component inside itself from only that string ?

thanks

  • Possible duplicate of [how do I manually sanitize in angular2](https://stackoverflow.com/questions/38577347/how-do-i-manually-sanitize-in-angular2) – Aravind Jul 16 '17 at 11:29
  • @Aravind the example you gave - they have strings with simple html, not html which must be handled by angular before. Or that does not matter for DomSanitize? – Andrey Ponomarenko Jul 16 '17 at 11:38

1 Answers1

3

The only option is to use JIT compiler and compile it when you get it. Read the Here is what you need to know about dynamic components in Angular, specifically Creating components on the fly part. It explains the process in details. Here is the gist:

class SomeComponent {
  @Input inputTpl;
  constructor(private _compiler: Compiler,
            private _injector: Injector,
            private _m: NgModuleRef<any>) {
  }

  ngOnChanges() {  
    const tmpCmp = Component({template: inputTpl})(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);
      })
    }
Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488
  • I got the following error : `ERROR Error: Template parse errors: Can't bind to 'placeholder' since it isn't a known property of 'am-input'.` But I've imported `am-input module` in the `parent module`. Though if I pass to `Component()(class {})` instead of empty class - the `the exact component class` (which I'm trying to dynamically generate) and same with `NgModule(..)(AmInputModule)` - everything is ok. But There are very many components which can be passed by `@Input`. It sounds sad if I need to pass in @Input not only code, but also component and module classes. How can I avoid that? – Andrey Ponomarenko Jul 16 '17 at 20:33
  • @AndreyPonomarenko, can you put your code in the question details or better yet create a plunker? – Max Koretskyi Jul 17 '17 at 05:25