我有一个大型应用程序,我刚刚开始升级到 Angular 2。我们使用了很多第三方和自制的自定义指令,我们将在 Angular 2 中替换这些指令,但没有时间立即执行。其中许多是表单元素小部件,例如 angular-ui。
在我们的 Angular 2 组件中,我想通过包装和升级包装器组件来弥合其中一些输入元素的差距。但是,我无法获得包装普通 <input>
的简单示例上类。
绑定(bind)并没有像我预期的那样双向进行。而且我不确定如何配置输出参数。
这是 Angular 1 组件的样子。
angular.module('app').component('ng1Wrapper', {
template: '<input type="text" ng-model="$ctrl.model" />',
bindings: { model: '=' }
});
将其升级为在 Angular 2 组件中使用的合适方法是什么?
我希望能够在 Angular 2 组件中使用它,例如:
<ng1-wrapper [(model)]="model.someProperty"></ng1-wrapper>
到目前为止,这是我尝试过的方法,但输出绑定(bind)并未更改 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);
}
}
最佳答案
有点晚了,但我最近也遇到了这个问题。您的解决方案很接近,但我发现使用 ngDoCheck
无效。删除它,它会按预期连接。
关于Angular2 upgradeComponent 如何进行双向绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41837204/