Skip to content

Angular Material: Not rendering using new Component() #26944

@greengooru

Description

@greengooru

Is this a regression?

  • Yes, this behavior used to work in the previous version

The previous version in which this bug was not present was

12.0.2

Description

I am loading an Angular Component using new Component(() . the component is actually shown on screen, but the Material Components are not rendered with the Styles or behaviors. However, if I use the same component code and load it using const {DynamicComponent} = await import("../app/dynamic/dynamic.component");, it works normally. So, I am not sure whether it is a real bug or I am missing something.

Surprisingly, this code works in Stackblits (https://stackblitz.com/edit/components-issue-rubl8b), but if you try to download this project in your desktop, install and run the Server, it does not work either. So, what am I missing here? Any help would be appreciated.

Reproduction

Steps to reproduce:

  1. Create an empty Angular 15.2.5
  2. Add this code to app.component.html: <div><button mat-button id="myId" (click)="loadModule()">Load Module</button></div><ng-template #container></ng-template>
  3. Add this code to àpp.component.ts:
@ViewChild('container', { read: ViewContainerRef })
container!: ViewContainerRef;

loadModule() {
    this.container.clear();
    const compMetadata = new Component({
      standalone: true,
      selector: 'selector',
      imports:[NgIf,
        MatFormFieldModule,
        MatInputModule,
        ReactiveFormsModule],
      schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
      template: `
      <mat-form-field class="example-full-width">
        <mat-label>First name</mat-label>
        <input matInput maxlength="10">
        <mat-hint>Errors appear instantly!</mat-hint>
        <mat-error *ngIf="true">
          First Name is <strong>required</strong>
        </mat-error>
      </mat-form-field>`,
      styles: [''],
    });
    const dynamicComponent = Component(compMetadata)(class MyCustomComponent {});
    const ref = this.container.createComponent(dynamicComponent as Type<unknown>);
}
  1. Add import "@angular/compiler"; to main.ts
  2. Run Server
  3. Test

Expected Behavior

It should show the Input with the Angular Material styles and behavior

Actual Behavior

It only shows a regular Input with the labels and no behavior.

Environment

  • Angular: 15.2.5
  • CDK/Material: 15.2.7
  • Browser(s): Edge and Chrome
  • Operating System (e.g. Windows, macOS, Ubuntu): Windows

Metadata

Metadata

Assignees

No one assigned

    Labels

    needs triageThis issue needs to be triaged by the team

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions