Search code examples
angulartypescripttwo-way-binding

Angular: Chained two-way property bind


I am trying to extend 3rd party component with some custom functionality by wrapping it into custom component.

But I am having issues with property binding - how do I create two-way property bind between parent, wrapper, and 3rd party component? (A chained-two-way bind property :)

So simplified html template would look like this

wrapper-component.html
<someCompotentToExtend [(ngModel)]="wrapProperty"></someCompotentToExtend>
}

wrapper-component.ts
export class WrapperComponent{
   wrapProperty:string=""
}

and in parent component i would do something like this

parent-component.html
<wrapper-component [(wrapProperty)]="parentProperty"></<wrapper-component>

parent-component.ts
export class ParentComponent{
   parentProperty:string=""
}

Changing any of these properties should update all other binded properties?

I ran a bunch of the test, i came close to solutions in these two examples but its too hacky and not working properly in the end

First solution

Using @Input @Output in wrapper component or on model change event. Wrapper component has a intermediary property, for example, wrapProperty which is bind to 3d party component or listening for changes. This will kindaaa work. In my case it is not what I want because after wrapper updates parent, parent will update wrapper component :??? :)

export class WrappedComponentComponent {
  wrapProperty:string=""

  @Input() set propertyFromParent(value: string) {    
    this.wrapProperty= value;
  }
  @Output() propertyFromParentChange= new EventEmitter();

Second solution

Using this framework ngx-context. It is really cool, creates a temporary local provider service through which you can share data. But it requires additional syntax when calling wrapper component and I need something that is more encapsulate.

It it possible to create a chained two-way binding system of properties? Thank you, any help is appreciated


Solution

  • Here is a working solution https://stackblitz.com/edit/angular-di6px5?file=app%2Fform.component.ts

    I accidentally made an error and used [(ngModel)] instead of separating them into [ngModel] and (ngModelChange). Separating allowed to have a better control of properties and avoid that extra update event i was receiving.