简体   繁体   中英

What is the replacement for the Angular Compiler in v14?

I am trying to upgrade to Angular 14. My current app uses the Compiler from '@angular/core' to compile angular templates at runtime. In order to use it I had to include the --aot=false flag when I built. I know has been deprecated for a few versions.

After upgrading, I am getting errors trying to build saying "template must be a string". This is in response to me attempting to create an angular Component at runtime.

Just to be clear, what I mean by an angular template string would be something like

    let angularTemplateString = 'Hello {{ firstNameFromPassedInContext }}';

They get much more complex, but that's the gist of it.

I suspect that there is still a way to compile angular templates at runtime in v14. Does anyone know how to do this, or if there is a better way to do this that is compatible with v14?

Is something like this what you are looking for?

@Component({
  selector: 'hello',
  template: '<div #container></div>',
})
export class HelloComponent implements AfterViewInit {
  @ViewChild('container', { read: ViewContainerRef })
  container: ViewContainerRef;

  constructor(private injector: Injector) {}

  ngAfterViewInit() {
    // Define the component using Component decorator.
    const component = Component({
      selector: 'test',
      template: '<div>This is the dynamic template. Test value: {{test}}</div>',
      styles: [':host {color: red}'],
    })(
      class {
        test = 'some value';
      }
    );

    // Define the module using NgModule decorator.
    const module = NgModule({ declarations: [component] })(class {});

    const componentRef = this.container.createComponent(component, {
      injector: this.injector,
      ngModuleRef: createNgModuleRef(module, this.injector),
    });
    setTimeout(() => (componentRef.instance.test = 'some other value'), 2000);
  }
}

Stackblitz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM