Home > Back-end >  How to check if component has specific @Inputs when using createComponent
How to check if component has specific @Inputs when using createComponent

Time:08-24

In my angular app I create components dynamically using the new createComponent function. I think this feature was added in v14.1. Anyway, this is my experiment

import { createComponent, .... } from '@angular/core';

@Directive({
    selector: '[myInjector]'
})
export class MyInjectorDirective {
    @Input() myInjector: any; // This will be the component

    ...

    ngOnInit() {
        const ref = createComponent(this.myInjector, {
            environmentInjector: this.envInjector,
            elementInjector: this.injector,
            hostElement: this.element.nativeElement
        });

        ref.setInput('test', 'value');
    }
}

The problem is that if the component I'm rendering doesn't have an input named test a console error is thrown. So I was wondering if there is a way to check what inputs a component has

I can work around this issue, if I give the input a default value

@Component({ ... })
export class SomeComponent  {
   @Input() test: string | null = null;
   ...
}

Then I check easily perform the check

ref.instance.test === null

Any suggestion how to do this?

CodePudding user response:

You can use reflectComponentType function to retrieve component metadata

const componentMetaData = reflectComponentType(this.myInjector);

componentMetaData.inputs //[{propName: 'propName', templateName: 'templateName'}]

For Reference

Example

  • Related