DEV Community

loading...

Angular: Pass Component via @Input() | HOC | Dynamic Wrapper

Eugene
Engineer, designer, researcher.
Updated on ・2 min read

The intro

I was working with React Projects for a long time. I have evolved a mindset that allows you to abuse HOC to make code more reusable and somewhat clean. But when I got into Angular, it felt weird at first that there is no such concept.

The spark

At some point, I got in touch with Modals and there it was the gong that awoke the ninja in me. First, I dove again into angular.io docs and indeed found a way to pass components through @Input() and render them. But that was unsatisfying because of the directive. That could be because decorators are something new after React. Or because it splits such a simple concept as HOC into too many files.

The sandbox

Here I have created a small code sandbox after my researches. You can see how a component can be rendered from a variable. I got deeper into Angular docs. Found a matching pattern between template variables and @directive. The directive was necessary only to extract reference to the element. As a result HOC got more simple and it is more close to the concept I got used to:

Ionic Modal Angular

async openModal() {
  const modal = await this.modalController.create({
    component: ModalWrapperComponent,
    componentProps: {
      bodyComponent: ModalComponent,
      bodyComponentInputs: { key: 'value' }
    },
  });

  modal.present();
}
Enter fullscreen mode Exit fullscreen mode

Material Dialog Angular

openDialog(): void {
  const dialogRef = this.dialog
    .open(ModalWrapperComponent, {
      width: "250px",
      data: {
        bodyComponent: ModalComponent,
        bodyComponentInputs: { key: 'value' }
      },
    });
}
Enter fullscreen mode Exit fullscreen mode

The takeaway

I just went geekserk after few weeks of Angular. So, this article emerged more because there were no good answers out there in the wild. Hope it helps anyone that wants to understand more deeply how angular works. And how to be a ninja with HOC in Angular.

For those who want a HOC with the less dynamic inner component. Here is a version with *ngTemplateOutlet. The difference is that this is more simple and cannot pass any inputs into the wrapped component.
https://stackblitz.com/edit/ionic-angular-dynamic-components-through-outlet?file=src/app/wrapper/wrapper.component.ts


May the bugs avoid you,
Eugene.

Discussion (0)