Get control properties inside control component

…衆ロ難τιáo~ 提交于 2019-12-12 18:24:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!