当您在ControlValueAccessor中“writeValue”时,为什么ngOnChanges没有触发?我通过registerOnChange发出了一些事件,但是在ngOnChanges中看不到任何 Action

const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR = new Provider(
  NG_VALUE_ACCESSOR, {
    useExisting: forwardRef(() => CustomInput),
    multi: true
  });

@Component({
  moduleId: module.id,
  selector: 'custom-input',
  templateUrl: 'custom-input.html',
  styleUrls: ['custom-input.css'],
  directives: [CORE_DIRECTIVES],
  providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})
export class CustomInput implements ControlValueAccessor{

  private _text: any = '';
  public isValid:boolean = false;


  onChange: EventEmitter<any> = new EventEmitter();
  onTouched: any;


  constructor(private ngControl:NgControl) {

  }

  ngOnChanges(e) {
    console.log('ngOnChanges');
  }

  get text(): any { return this._text; };

  set text(v: any) {
    if (v !== this._text) {
      this._text = v;
      this.onChange.emit(v);
    }
  }

  writeValue(v) {
    this.text = v;
  }
  registerOnChange(fn): void {
    this.onChange.subscribe(fn);
  }
  registerOnTouched(fn): void {
    this.onTouched = fn;
  }

}

最佳答案

ngOnChanges属性更改时,会调用@Input()

假设您的自定义输入具有text属性:

export class CustomInput implements OnChanges {
    @Input() text;

    ngOnChanges() {
        console.log('ngOnChanges');
    }
}

然后在ngOnChanges更改时将调用someVariable:
<custom-input [text]="someVariable"></custom-input>

从组件内部进行的更改不会触发回调。 ngOnChanges纯粹用于输入。

https://angular.io/guide/lifecycle-hooks#lifecycle-sequence

注意:ngOnChangesngOnInit之前也被调用

09-25 19:37