我创建了一个自定义输入组件,但我想处理组件内部的错误。因此,为了使验证工作,我需要从控制对象中获取错误。有可能吗?
我的组件与here完全相同。
组件的顶部:
@Component({
selector: 'sc-input',
styles,
template: `
<label class="label">
<ng-content></ng-content>
<input class="input" [(ngModel)]='value' [attr.name]='name' [attr.type]='type'
(blur)='onBlur($event)' (focus)='onFocus($event)'>
<div class="errors">
<div class="errors__messages"><ng-content select="sc-error-messages"></ng-content></div>
<div class="errors__indicator"></div>
</div>
</label>
`,
providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})
export class CustomInputComponent implements ControlValueAccessor {
...
}
解决问题:主机类,但仍想知道是否有办法在其组件内部获得控制权。
答案 0 :(得分:2)
我认为这应该仍然适用于新的表单模块:
export class CustomInputComponent implements ControlValueAccessor {
constructor(private control:NgControl, private ngModel:NgModel) {}
}
<强>更新强>
刚刚找到https://github.com/angular/angular/issues/7391#issuecomment-246120184
建议
constructor(private _injector:Injector) {
this.control = this._injector.get(NgControl).control;
}