Angular standalone dynamic components and Material Modules

714 Views Asked by At

I'm using dynamic components (angular v16) to dynamically render a template. For generic templates with standard html everything works fine, but cannot find a way to use components from material modules (like mat-icon) inside the template.

It looks like material component module imports ,declared in the standalone dynamic component, like MatIconModule, are not imported or are being tree-shaked (removed) by the compiler (in dev mode). The following is a simple example:

[...]

 @ViewChild('container', {read: ViewContainerRef, static: true}) container: ViewContainerRef;

[...]

let tpl = `
 <div>
   <mat-icon aria-label="error: mat-icon is not a known element" fontIcon="home"></mat-icon>
   <div>Hello</div>
   <testcomponent>this works ok</testcomponent>
 </div>
`

let component = Component({
        standalone: true,
        selector: 'cp1',
        template: tpl,
        imports: [
            CommonModule, NgIf, NgFor, MatIconModule, MyTestComponent
        ]
    })
    (class DynamicComponentImpl extends DynamicComponent {
        constructor() {
            super();
        }
    })

 container.createComponent(component, {injector: container.injector})  

So my question is, is there a way to use material modules inside dynamically created standalone components?

I'm able to make it work using the compiler and module factories but this.compiler.compileModuleAndAllComponentsSync and other methods are deprecated now and i'm trying to find another way to achieve the same result.

[...]
const module = this.compiler.compileModuleAndAllComponentsSync(TemplateModule);
const factory = module.componentFactories.find((comp) =>
comp.componentType === TemplateComponent
);
const component = this.container.createComponent(factory);
[...]
0

There are 0 best solutions below