Angular2 @Input到具有get/set的属性

Pau*_*cas 136 angular

我在该组件中有一个Angular2组件,它当前有一些字段,在它们之前应用@Input()以允许绑定到该属性,即

@Input() allowDay: boolean;
Run Code Online (Sandbox Code Playgroud)

我想要做的是实际使用get/set绑定到一个属性,这样我就可以在setter中做一些其他的逻辑,如下所示

_allowDay: boolean;
get allowDay(): boolean {
    return this._allowDay;
}
set allowDay(value: boolean) {
     this._allowDay = value;
     this.updatePeriodTypes();
}
Run Code Online (Sandbox Code Playgroud)

我如何在Angular2中做到这一点?

根据Thierry Templier的建议我将其更改为,但是抛出错误无法绑定到'allowDay',因为它不是已知的本机属性:

//@Input() allowDay: boolean;
_allowDay: boolean;
get allowDay(): boolean {
    return this._allowDay;
}
@Input('allowDay') set allowDay(value: boolean) {
    this._allowDay = value;
    this.updatePeriodTypes();
}
Run Code Online (Sandbox Code Playgroud)

Thi*_*ier 217

您可以直接在setter上设置@Input,如下所述:

_allowDay: boolean;
get allowDay(): boolean {
    return this._allowDay;
}

@Input('allowDay')
set allowDay(value: boolean) {
    this._allowDay = value;
    this.updatePeriodTypes();
}
Run Code Online (Sandbox Code Playgroud)

请参阅此plunkr:https://plnkr.co/edit/6miSutgTe9sfEMCb8N4p ? p = preview .

  • *警告*:`设置器'不会**被通过引用传递的值的突变(即,推入数组,改变对象等)触发。您需要替换作为“输入”传递的整个值,以使“设置者”再次触发。 (8认同)
  • 这是一个坏主意,因为如果您使用 setter,ngOnChanges 不会触发。 (4认同)
  • [在角度基础页面上](https://angular.io/guide/component-interaction#intercept-input-property-changes-with-a-setter) (4认同)

Mar*_*der 47

如果您主要对仅为setter实现逻辑感兴趣:

import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';

// [...]

export class MyClass implements OnChanges {
  @Input() allowDay: boolean;

  ngOnChanges(changes: SimpleChanges): void {
    if(changes['allowDay']) {
      this.updatePeriodTypes();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

SimpleChanges如果更改哪个输入属性或者只有一个输入属性无关紧要,则不需要导入.

Angular Doc:OnChanges

除此以外:

private _allowDay: boolean;

@Input() set allowDay(value: boolean) {
  this._allowDay = value;
  this.updatePeriodTypes();
}
get allowDay(): boolean {
  // other logic
  return this._allowDay;
}
Run Code Online (Sandbox Code Playgroud)

  • "使用ngOnChanges与不使用set"没有区别...... ;;)开玩笑:如果你的组件有多个`@Input`属性并且你想在任何一个例程发生变化时调用例程,那么一个好处是.因此需要的代码更少. (4认同)
  • @MA-Maddin 我想如果您期望同时进行多个更改,并且每个更改都会导致需要运行的例程,那么您也可以设置一个去抖的可观察值。 (2认同)

max*_*ode 6

@Paul Cavacas,我​​有同样的问题,我通过Input()在吸气剂上方设置装饰器来解决.

  @Input('allowDays')
  get in(): any {
    return this._allowDays;
  }

  //@Input('allowDays')
  // not working
  set in(val) {
    console.log('allowDays = '+val);
    this._allowDays = val;
  }
Run Code Online (Sandbox Code Playgroud)

看到这个plunker:https://plnkr.co/edit/6miSutgTe9sfEMCb8N4p ? p = preview

  • 这个错误让我抓狂,我终于发现你应该首先定义Input()(getter或setter但输入装饰器必须先行) (6认同)