Home > Software engineering >  One way binding does not work on dynamic created components in Angular?
One way binding does not work on dynamic created components in Angular?

Time:08-05

I have created the following StackBlitz

https://stackblitz.com/edit/angular-ivy-zdknmx?file=src/app/app.component.ts

Basically I have a simply component

@Component({
  selector: 'foo-component',
  template: `
    <p>{{ databearer.content }} {{databearer.index}}</p>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class FooComponent implements OnChanges {
  @Input() databearer: any;

  ngOnChanges(changes: SimpleChanges): void {
    console.info(changes);
  }
}

Which I have added one in normal way, and another one dynamically. The one which I have added in normal way the one-way-binding works as expected. But the one which I have added dynamically the one-way-binding does not work.

I'm wondering whether I have done something wrong, or perhaps one-way-binding does not work for dynamically created components in Angular 14?

CodePudding user response:

since the dynamic component is not bound anywhere via @Input(), that means angular has no way of "guessing" what has changed already. so you need to the ff below everytime you increment the value of dataBearer2:

componentRef.instance.databearer = { ...this.databearer2 };
componentRef.instance.cdRef.detectChanges()

and in your foo component add this

constructor(public cdRef: ChangeDetectorRef) {}

a popular solution to this types of problem would be to use observables instead so you can simply use the async pipe. (but judging from your code it looks like thats not what you want right now)

  • Related