首页 文章

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

提问于
浏览
99

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

@Input() allowDay: boolean;

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

_allowDay: boolean;
get allowDay(): boolean {
    return this._allowDay;
}
set allowDay(value: boolean) {
     this._allowDay = value;
     this.updatePeriodTypes();
}

我如何在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();
}

4 回答

  • 5

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

    _allowDay: boolean;
    get allowDay(): boolean {
        return this._allowDay;
    }
    
    @Input('allowDay')
    set allowDay(value: boolean) {
        this._allowDay = value;
        this.updatePeriodTypes();
    }
    

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

  • 152

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

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

    如果更改了哪个输入属性或者只有一个输入属性并不重要,则不需要导入 SimpleChanges .

    Angular Doc: OnChanges

    otherwise:

    private _allowDay: boolean;
    
    @Input() set allowDay(value: boolean) {
      this._allowDay = value;
      this.updatePeriodTypes();
    }
    get allowDay(): boolean {
      // other logic
      return this._allowDay;
    }
    
  • 37

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

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

  • 1

    在stackblitz上更新了对角度7.0.1的已接受答案:https://stackblitz.com/edit/angular-inputsetter?embed=1&file=src/app/app.component.ts

    directives 在组件装饰器选项中不再存在 . 所以我向app模块提供了sub指令 .

    谢谢@thierry-templier

相关问题