问题
I created a custom input component but I want to work with errors inside the component. So to make validation work I need to get errors from control object. Is it possible?
I did my component exactly like here.
Top part of the component:
@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 {
...
}
Solved problem by :host classes, but still want to know if there is a way to get control inside its component..
回答1:
I think this should still work in the new forms module:
export class CustomInputComponent implements ControlValueAccessor {
constructor(private control:NgControl, private ngModel:NgModel) {}
}
Update
Just found https://github.com/angular/angular/issues/7391#issuecomment-246120184
It suggests
constructor(private _injector:Injector) {
this.control = this._injector.get(NgControl).control;
}
来源:https://stackoverflow.com/questions/39409006/get-control-properties-inside-control-component