Mak*_*kyi 14 javascript angular-cli angular
我正在尝试实现一个自定义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>
Run Code Online (Sandbox Code Playgroud)
国家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>
Run Code Online (Sandbox Code Playgroud)
国家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;
}
...
}
Run Code Online (Sandbox Code Playgroud)
完整的代码存在于此:https://github.com/maksymzav/ngcontrol.
在JIT模式下运行代码时,代码运行正常.我想因为在运行时它确实知道它使用了哪个控件:NgModel,或FormControlName,或FormControlDirective.但是,当我运行AOT构建时,ng build --prod它失败并显示消息
错误输入:没有NgControl的提供者("[错误 - >] <app-country-select> </ app-country-select>")
有谁知道如何使这个构建成功?谢谢.
im.*_*tov 15
您可以添加@Optional()装饰器到您的controlDir.
将依赖项标记为可选的参数元数据.如果未找到依赖项,则Injector提供null.
在我的情况下,这解决了"无提供者"错误,我能够成功编译项目.
例:
constructor(
@Optional() // Add this decorator
@Self()
public controlDir: NgControl,
private stripe: StripeService,
private cd: ChangeDetectorRef
) {
// Better to add some checks here since controlDir can be null
if (controlDir) {
controlDir.valueAccessor = this;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4785 次 |
| 最近记录: |