'Passing data into @Input() of a dynamically generated component works in stackblitz but not on my own computer

I'm dynamically creating a component in Angular 13 with ViewContainerRef.createComponent() like so

const componentInstance : ComponentRef<unknown> = this.vcRef.createComponent(YourComponent);

There's instances where I want to pass data into the component before embedding it into the view which at first I couldn't figure out how to do but when making this stackblitz to highlight the problem I wound up coming up with a solution by doing this

componentInstance.instance['PropName'] = 'some value';

On my computer however it won't compile because I get an Object is of type unknown error. Can someone explain why this is happening?



Solution 1:[1]

That's because you assign a YourComponent type to unknown type like below:

const componentInstance : ComponentRef<unknown> = this.vcRef.createComponent(YourComponent);

Then try to access the property:

componentInstance.instance['PropName'] = 'some value';

Solution 1

To resolve that, you first need to type guard the unknown type before using it:

if(componentInstance instanceof YourComponent)
  componentInstance.instance['PropName'] = 'some value';

And that's basically unknown is used for. It's used when we don't know type beforehand. Then we have a bunch of type guard to funnel it to the right type before we call its functions/properties.

example:

function print(x: unknown) {

  if(typeof x === 'string')
    return 'x is string';
  
  if(x instanceof YourComponent)
    return x.name;
}

Solution 2

Another solution is to give the actual type during the assignment:

const componentInstance : ComponentRef<YourComponent> = this.vcRef.createComponent(YourComponent);

Solution 3

OR not giving any explicit type at all since TypeScript can infer the type from the left hand side of the assignment:

const componentInstance = this.vcRef.createComponent(YourComponent);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1