0

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?

2
  • not sure how it works on the static component, but why are you creating a new object each time the counter changes? Commented Aug 4, 2022 at 17:35
  • @LielFridman because of the following changeDetection: ChangeDetectionStrategy.OnPush, otherwise Angular wouldn't detect changes. I could remove this to opt for the default strategy. But I'm thinking long term it is better to update this way instead. Commented Aug 4, 2022 at 18:53

1 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

thanks I think this is what I'm looking for. yes there's the alternative with observable. I also found that using set/get would also work. but really wanted the one-way-binding to work.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.