Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 upgradeComponent how to do 2-way binding

I have a large application that I am just beginning to upgrade to Angular 2. We use a lot of third party and homegrown custom directives that we will replace in Angular 2, but do not have the time to do it right away. Many of these are form element widgets like angular-ui.

In our Angular 2 components I would like to bridge the gap for some of these input elements by wrapping them and upgrading the wrapper component. However, I cannot get a simple example of wrapping a plain <input> to work.

The binding is not going both ways like I expect. And I am not sure how to configure the Output parameter.

Here is what the Angular 1 component looks like.

angular.module('app').component('ng1Wrapper', {
  template: '<input type="text" ng-model="$ctrl.model" />',
  bindings: { model: '=' }
});

What would be the appropriate way to upgrade this to use inside an Angular 2 component?

I'd like to be able to use it in Angular 2 component like:

<ng1-wrapper [(model)]="model.someProperty"></ng1-wrapper>

This is what I've tried so far, but the output binding is not changing the model's property in Angular 2. I need to capture user's input from this wrapped directive, but also pass in default values.

import {
Directive, DoCheck, ElementRef, EventEmitter, Injector, Input, Output } from '@angular/core';
import { UpgradeComponent } from '@angular/upgrade/static';
@Directive({
  selector: 'ng1-wrapper'
})
export class Ng1WrapperDirective extends UpgradeComponent implements DoCheck {
  @Input() model: any;
  @Output() modelChange: EventEmitter<any> = new EventEmitter<any>();

  constructor(elementRef: ElementRef, injector: Injector) {
      super('ng1Wrapper', elementRef, injector);
  }

  ngDoCheck() {
      super.ngDoCheck();
      this.modelChange.next(this.model);
  }
}
like image 487
kevinrstone Avatar asked Mar 20 '26 20:03

kevinrstone


1 Answers

A little late, but I recently ran into this problem too. The solution you had was close, but I found that using ngDoCheck didn't work. Remove that, and it wires up as expected.

like image 200
bensgroi Avatar answered Mar 23 '26 13:03

bensgroi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!