我有一个自定义表单控件,它实现 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() 中定义,但它始终未定义或为空。至少在第一次运行中。这是我的控制台日志:
ngOnInit undefined
ngDoCheck undefined
writeValue null
ngAfterContentInit null
ngAfterContentChecked null
ngAfterViewInit null
ngAfterViewChecked null
---
writeValue true
ngDoCheck true
ngAfterContentChecked true
ngAfterViewChecked true
为什么 value 总是 undefined/null ,有没有办法改变它?