【发布时间】:2017-12-19 11:53:11
【问题描述】:
我正在尝试按照 Kara Erickson 在上次 Angular Connect https://youtu.be/CD_t3m2WMM8?t=20m22s 上推荐的那样实现自定义 ControlValueAccessor。将有效性状态从父组件传递给子组件。
app.component.html:
<app-country-select ngModel="model" name="country-select"></app-country-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>
国家选择.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 构建时,它会失败并显示消息
错误:没有 NgControl 提供程序 ("[ERROR ->]
")
有谁知道如何使这个构建成功?谢谢。
【问题讨论】:
-
您可能忘记将生成的html包装在表单标签中。
-
也可以看到这篇文章:stackoverflow.com/questions/37284763/…
-
@Igor,你的意思是将app.component.html中的代码包装到form标签中吗?不幸的是,这无济于事。
-
@lemmingworks,你写的帖子是关于 angular2 使用表单的方式,当没有模块时。我同时导入了 FormsModule 和 ReactiveFormsModule,所以所有指令都应该在里面。
-
你有没有想过这个问题?
标签: javascript angular angular-cli