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

2
  • Possible duplicate of how do I manually sanitize in angular2 Commented Jul 16, 2017 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? Commented Jul 16, 2017 at 11:38

1 Answer 1

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);
      })
    }
Sign up to request clarification or add additional context in comments.

2 Comments

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?
@AndreyPonomarenko, can you put your code in the question details or better yet create a plunker?

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.