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?
You can use reflectComponentType
function to retrieve component metadata
const componentMetaData = reflectComponentType(this.myInjector);
componentMetaData.inputs //[{propName: 'propName', templateName: 'templateName'}]