Search code examples
angulartypescriptngonchanges

Angular fire OnChanges to dynamic child by typescript (NO HTML)


I'm creating my component by Typescript and passing from there my inputs to my child.

parent TS

this.childComponent = this.viewContainerRef.createComponent(this.data.body).instance;
this.childComponent['childInput'] = 5;

child TS

@Input() childInput!: number;
ngOnChanges(changes: SimpleChanges): void {
    if(changes['childInput'].previousValue !== changes['childInput'].currentValue)
    console.log('change fired')
}

how can I fire from parent the OnChanges?

I tryed this.childComponent.onChanges(); but it was not working because I didn't past any params

thanks


Solution

  • If you are using Angular v14.1.0

    You can use setInput method on componentRef to set Input dynamically. It will automatically trigger ngOnChanges whenever value changes

    this.childComponent = this.viewContainerRef.createComponent(this.data.body);
    this.childComponent.setInput('childInput',5);
    

    Sample Working Example