angular - 获取控件组件内的控件属性

标签 angular angular2-forms

我创建了一个自定义输入组件,但我想处理组件内部的错误。因此,为了进行验证,我需要从控制对象中获取错误。可能吗?

我的组件与 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 {
  ...
}

通过 :host 类解决了问题,但仍然想知道是否有办法在其组件内部获得控制权..

最佳答案

我认为这应该在新的表单模块中仍然有效:

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;
}

关于angular - 获取控件组件内的控件属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39409006/

相关文章:

angular - SVG 标记方向箭头出现在 DOM 中,但标记本身不可见

angular - ngx-chips:无法从 autocompleteItems 添加第二个标签

javascript - 突出显示 html 原始文本中的特定文本

具有来自@Input 的值的angular2 ngModel

javascript - Angular2 表单页面重新加载?

javascript - 如何捕获http状态

angular - 在 npm 中安装新依赖项时 RXJS 版本不匹配

rest - Angular 2 http post 返回 200 但没有返回响应

typescript - 检查 FormArray 中的所有复选框 - Angular 2 Reactive Form

angular - 如何绑定(bind)到angular2 beta 6中的单选按钮