在Angular2上传播计算值的正确方法

时间:2017-05-04 16:20:48

标签: javascript angular typescript

我想通过@Input属性

使用计算值

但传播初始值并不奏效。

https://plnkr.co/edit/1MMpOYOKIouwnNc3uIuy

我创建App(带有模板驱动形式的根组件)和NumComponent(只保存类型化值的子组件)组件。

当我将属性传递给NumComponent之类的[useThree]="true"时,我希望将默认值“3”设置为NumComponent

但是,如果不使用setTimeout

,我就找不到办法

是否可以在没有setTimeout的情况下传播初始值?

编辑于5/5

应用组件

@Component({
  selector: 'my-app',
  template: `
    <div>
      <form novalidate #form="ngForm">
        <app-num name="num" ngModel [useThree]="true"></app-num>
      </form>
      <pre>{{form.value | json}}</pre>
    </div>
  `
})
export class App {}

NumComponent

export const NumValueAccessor = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => NumComponent),
  multi: true
};

@Component({
  selector: 'app-num',
  template: `<input [(ngModel)]="num" type="text" (ngModelChange)="updateValue()" />`,
  providers: [NumValueAccessor]
})
export class NumComponent implements ControlValueAccessor {
  num = 0;

  // I want set literal number 3 to `num` property
  // when `useThree` is true.
  @Input() useThree = false;

  onChange = (_: any) => {};

  updateValue(num = this.num) {
    this.onChange(String(num));
  }

  writeValue(value: string): void {
    if (this.useThree) {
      /**********
       * ISSUE
       **********/
      // this code is not work. after code ran, `NumComponent` has
      // value 3 but AppComponent's internal FormComponent value
      // is '' (empty string)
      // this.num = 3;
      // this.updateValue(3);

      // ran code with `setTimeout` solve this problem. but
      // I don't want using setTimeout for this feature.
      // setTimeout(() => {
      //   this.num = 3;
      //   this.updateValue(3);
      // }, 0);

      // Is there any way to propagate computed initial value?
      this.num = 3;
      this.updateValue(3);

      /**********
       * ISSUE
       **********/

      this.useThree = false;
      return;
    }
    this.num = Number(value);
  }

  registerOnChange(fn: any): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: any): void {}

  setDisabledState(isDisabled: boolean): void {}
}

似乎父组件在初始化生命周期时没有实现传播值。

1 个答案:

答案 0 :(得分:0)

我不确定我是否完全理解了这个问题,但是你正在寻找的一个可能的解决方案可能是

private _useThree = false;
@Input() set useThree(value: boolean) {
     this._useThree = value;
     if (this._useThree) {
         this.num = 3;
     }
}

这样,只要你想从父组件设置输入useThree属性的值,就可以实际执行上面定义的setter方法的代码。