为什么在使用[ngModel] =“ true”时在每个生命周期挂钩上都未定义this.value / null

时间:2019-09-13 06:59:29

标签: angular forms typescript lifecycle-hook react-lifecycle-hooks

我有一个自定义表单控件,该控件实现ControlValueAccessor来处理[(formControl)]="..."[(ngModel)]="..."

@Component({
  selector: 'app-foo',
  templateUrl: './foo.component.html',
  styleUrls: ['./foo.component.css'],
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => FooComponent),
            multi: true,
        },
    ],
})
export class FooComponent implements ControlValueAccessor, OnInit, AfterContentInit, OnInit, OnChanges, DoCheck, AfterContentChecked, AfterViewInit, AfterViewChecked {

  constructor() { }

  ngOnChanges() {
    console.log('ngOnChanges', this.value);
  }
  ngOnInit() {
    console.log('ngOnInit', this.value);
  }
  ngDoCheck() {
    console.log('ngDoCheck', this.value);
  }
  ngAfterContentInit() : void {
    console.log('ngAfterContentInit', this.value);
  }
  ngAfterContentChecked() : void {
    console.log('ngAfterContentChecked', this.value);
  }
  ngAfterViewInit() : void {
    console.log('ngAfterViewInit', this.value);
  }
  ngAfterViewChecked() : void {
    console.log('ngAfterViewChecked', this.value);
  }

  /**
   * Write a new value to the element.
   */
  public writeValue(value : any) : void { // tslint:disable-line:no-any
    this._value = value;
    console.log('writeValue', this.value);
  }

  ...

我这样使用该组件:

<app-foo [ngModel]="true"></app-foo>

我假设该值至少应在ngAfterContentInit()中定义,但始终未定义或为null。至少在第一次运行中。这是我的控制台日志:

ngOnInit undefined
ngDoCheck undefined
writeValue null
ngAfterContentInit null
ngAfterContentChecked null
ngAfterViewInit null
ngAfterViewChecked null
---
writeValue true
ngDoCheck true
ngAfterContentChecked true
ngAfterViewChecked true

为什么值总是不确定/为空,并且有办法改变它?

1 个答案:

答案 0 :(得分:1)

您需要实现ControlValueAccessor才能使其起作用:

export class FooComponent implements ControlValueAccessor {
  writeValue(value) {
   this._value = value;
  }
  ...
}

writeValue的输入值更改时,将执行ngModel函数。您还必须实现registerOnTouchregisterOnChange

请查看此alligator.io article,以获取更多信息。