如何在降级的 Angular 组件上实现 ControlValueAccessor

How to implement ControlValueAccessor on downgraded Angular component

我有一个实现 ControlValueAccessor 的 Angular 组件,但是从未使用 ngModel 的初始值调用 writeValue 方法。

模板:

<my-comp [(ngModel)]="$ctrl.activeUser"></my-comp>

组件通过以下方式降级为 AngularJS:

.directive('myComp', downgradeComponent({
  component: MyComp,
  inputs: [],
  outputs: [],
}));

我尝试将 ngModel 添加到 inputsoutputs 但它不起作用。

你应该使用 ng-model 属性而不是 [(ngModel)],像这样:<my-comp ng-model="$ctrl.activeUser"></my-comp>

来自 angular 文档:

 * 3. `ng-model` is controlled by AngularJS and communicates with the downgraded Angular component
 *    by way of the `ControlValueAccessor` interface from @angular/forms. Only components that
 *    implement this interface are eligible.
 *
 * ## Supported Features
 *
 * - Bindings:
 *   - Attribute: `<comp name="World">`
 *   - Interpolation:  `<comp greeting="Hello {{name}}!">`
 *   - Expression:  `<comp [name]="username">`
 *   - Event:  `<comp (close)="doSomething()">`
 *   - ng-model: `<comp ng-model="name">`