Angular2 @Input to a property with get/set

前端 未结 4 1252
故里飘歌
故里飘歌 2020-11-30 19:58

I have an Angular2 component in that component it currently has a bunch fields that have @Input() applied before them to allow binding to that property, i.e.



        
4条回答
  •  心在旅途
    2020-11-30 20:31

    If you are mainly interested in implementing logic to the 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();
        }
      }
    }
    

    The import of SimpleChanges is not needed if it doesn't matter which input property was changed or if you have only one input property.

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

提交回复
热议问题