我正在尝试实现一个自定义ControlValueAccessor,就像Kara Erickson在最后一个Angular Connect https://youtu.be/CD_t3m2WMM8?t=20m22s上推荐的那样 . 将有效状态从父组件传递给子组件 .
app.component.html:
<app-country-select ngModel="model" name="country-select"></app-country-select>
国家select.component.html:
<select [formControl]="controlDir.control" #select placeholder="Country" i18n-placeholder (click)="onTouched()"
(change)="onChange($event.value)" [required]="required">
<option value="at">Austria</option>
<option value="au">Australia</option>
</select>
国家select.component.ts:
@Component({
selector: 'app-country-select',
templateUrl: './country-select.component.html',
styleUrls: ['./country-select.component.scss'],
})
export class CountrySelectComponent implements ControlValueAccessor {
@Input() required = false;
@ViewChild('select') select: HTMLSelectElement;
onChange: (value: any) => void;
onTouched: () => void;
constructor(@Self() public controlDir: NgControl) {
controlDir.valueAccessor = this;
}
...
}
完整代码住在这里:https://github.com/maksymzav/ngcontrol .
在JIT模式下运行代码时,代码运行正常 . 我想因为在运行时它确实知道它使用了哪个控件:NgModel,或FormControlName,或FormControlDirective . 但是当我使用 ng build --prod
运行AOT构建时,它会失败并显示消息
ERROR in:没有NgControl的提供者(“[ERROR - >] <app-country-select> </ app-country-select>”)
有谁知道如何使这个构建成功?谢谢 .
1 回答
您可以将@Optional()装饰器添加到
controlDir
.在我的情况下,这解决了“无提供者”错误,我能够成功编译项目 .
例: