【问题标题】:Custom two way binding and @Input mismatch in Angular?Angular中的自定义双向绑定和@Input不匹配?
【发布时间】:2017-09-21 01:46:28
【问题描述】:

我已经阅读了article 关于 Angular 中两种方式的绑定。
此外 - Angular 文档提供了访问内部组件属性的示例。

在它的父组件中:

 <name-child *ngFor="let name ..." [name]="name"></name-child>

其中[name] 指的是内部setter(!):

 @Input()
 set name(name: string) {
    this._name =...;
  }

这很清楚。

但后来我看到了下面这个例子(here)

<custom-counter [(counter)]="counterValue"></custom-counter>

counter 在内部组件中作为 GETTER 上的 @Input !

    @Input()       // <--------     On a getter ??
    get counter()
    {
        return this.counterValue;
    }

    set counter(val)
    {
        this.counterValue = val;
        this.counterChange.emit(this.counterValue);
    }

问题

plnkr 中的代码确实按预期工作,但是 - 我不明白它如何与 getter 上的 @Input 一起工作!

我的意思是 - 父级应该将值设置为内部设置器。

我错过了什么?

PLNKR

【问题讨论】:

  • @yurzui 所以我设置它并不重要? (编辑,测试,相同的生成代码 - 所以没关系)
  • 好像是这样。您可以将装饰器移动到设置器,但只会创建一个属性,因此将被装饰

标签: javascript angular


【解决方案1】:

您始终可以使用 Playground 来检查 typescript 在内部的作用

例如这段代码:

class MyClass {
    @Input()       // <--------     On a getter ??
    get counter()
    {
        return this.counterValue;
    }

    set counter(val)
    {
        this.counterValue = val;
        this.counterChange.emit(this.counterValue);
    }
}

将被翻译成

var MyClass = (function () {
    function MyClass() {
    }
    Object.defineProperty(MyClass.prototype, "counter", {
        get: function () {
            return this.counterValue;
        },
        set: function (val) {
            this.counterValue = val;
            this.counterChange.emit(this.counterValue);
        },
        enumerable: true,
        configurable: true
    });
    return MyClass;
}());
__decorate([
    Input() // <--------     On a getter ??
], MyClass.prototype, "counter", null);

如您所见,只有一个属性名称为 counter,它将使用 @Input 装饰器进行装饰。

【讨论】:

  • 顺便说一句,我确实在 TS Playground 上玩了很多,但我并没有想到装饰器及其在 TS 中的影响。直到。
猜你喜欢
  • 1970-01-01
  • 2018-07-26
  • 1970-01-01
  • 2015-01-19
  • 2018-01-08
  • 1970-01-01
  • 2017-06-19
  • 2016-06-10
  • 1970-01-01
相关资源
最近更新 更多