0

I am trying to compile some HTML content in Angular 4, which can be done by $compile in Angular 1.

I tried some suggested alternatives of Angular 2, which are also deprecated.

Some one suggest me the best way to do.

Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488

1 Answers1

0

The replacement of $compiler service in Angular is a Compiler. You can inject it like this:

class MyComponent {
     constructor(compiler: Compiler) {}

Read the article Here is what you need to know about dynamic components in Angular to understand how it can be used to dynamically compile components.

Here is an example from the article:

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 = this.vc.createComponent(tmpCmp);
      cmpRef.instance.name = 'dynamic';
    })
}
Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488
  • In this approach how can we trigger parent component functions? – Harsha Vardhan Putrevu Nov 24 '17 at 12:21
  • when and why do you need to trigger them? – Max Koretskyi Nov 24 '17 at 16:22
  • 1
    I mean I want to add a button and by clicking on it, want to call patent component function. – Harsha Vardhan Putrevu Nov 24 '17 at 17:21
  • @HarshaVardhanPutrevu, did you figure it out? where do you want to add a button? add details to your question using code from my answer – Max Koretskyi Nov 29 '17 at 08:17
  • I think it's pretty obvious what @HarshaVardhanPutrevu is asking. He has, like I do, a (click) directive in an injected element. How do we "compile" the thing so it will actually call the method referenced by the (click). Seems pretty simple. In AngularJS it was a single line of code. I am now seeing solutions that require templates and hundreds of lines of code to accomplish the same thing. – iGanja Jan 18 '20 at 04:34