简体   繁体   English

Angular2 upgradeComponent如何做双向绑定

[英]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. 我有一个大型应用程序,我刚刚开始升级到Angular 2.我们使用了许多第三方和自行开发的自定义指令,我们将在Angular 2中替换它们,但没有时间立即执行。 Many of these are form element widgets like angular-ui. 其中许多都是像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. 在我们的Angular 2组件中,我想通过包装它们并升级包装器组件来弥补其中一些输入元素的间隙。 However, I cannot get a simple example of wrapping a plain <input> to work. 但是,我无法得到一个包含普通<input>的简单示例。

The binding is not going both ways like I expect. 绑定并不像我期望的那样双向。 And I am not sure how to configure the Output parameter. 我不知道如何配置Output参数。

Here is what the Angular 1 component looks like. 这是Angular 1组件的样子。

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? 升级它以在Angular 2组件中使用的适当方法是什么?

I'd like to be able to use it in Angular 2 component like: 我希望能够在Angular 2组件中使用它,如:

<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. 这是我到目前为止所尝试的,但输出绑定并未改变Angular 2中模型的属性。我需要从此包装指令捕获用户的输入,但也传递默认值。

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. 你的解决方案很接近,但我发现使用ngDoCheck不起作用。 Remove that, and it wires up as expected. 删除它,并按预期连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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