简体   繁体   中英

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);
  }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM