创建简单的输入组件失败

时间:2017-10-08 01:20:33

标签: html angular

我尝试创建一个输入组件,它处理一些逻辑并停止复制和粘贴HTML代码。

因此我添加了input.component.ts

import { Component, Input } from '@angular/core';

@Component({
    selector: 'input-component',
    templateUrl: 'input.component.html'
})

export class InputComponent {
  @Input()
  public type;

  @Input()
  public id;

  @Input()
  public label;

  @Input()
  public formControlName;

  @Input()
  public cssClasses;

  @Input()
  public withErrors = false;

  @Input()
  public error;

  @Input()
  public controls;

  public isFocused: boolean;
}

此组件的模板是input.component.html

<input id="{{ id }}"
   class="{{ cssClasses }}"
   type="{{ type }}"
   [ngClass]="{
            'has-error': error && !isFocused,
            'not-empty': controls.value && controls.value.length > 0
            }"
   spellcheck=false
   (focus)="isFocused = true"
   (blur)="isFocused = false">
<label for="{{ id }}" [ngClass]="{'has-error': error && !isFocused}">{{ label }}</label>
<div id="formErrors-{{ id }}" *ngIf="error && !isFocused && withErrors" class="alert help-block with-errors">
    {{ error }}
</div>

这是否可能,或者如果没有,是否有正当理由不再考虑它?

如果我可以这样调用InputComponent会很棒:

     <input-component
    [type]="'text'"
    [id]="'streetName'"
    [label]="'Street'"
    [formControl]="'street'"
    [cssClasses]="'form-control width-100'"
    [withErrors]="true"
    [error]="formErrors['street']"
    [controls]="addressDataForm.controls['street']"></input-component>

我创建了这个,但直到现在我总是收到以下错误:

Error: No value accessor for form control with unspecified name attribute Error: No value accessor for form control with unspecified name attribute

DOM看起来input.component.ts中的属性未在模板中呈现:

<input-component ng-reflect-type="text" ng-reflect-id="streetName" ng-reflect-label="Street"
             ng-reflect-css-classes="form-control width-100" ng-reflect-with-errors="true" ng-reflect-error=""
             ng-reflect-controls="[object Object]">
    <input spellcheck="false">
    <label></label>
    <!---->
</input-component>

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

  

错误:没有带有未指定名称的表单控件的值访问器   属性

您应为自定义组件指定ngDefaultControl属性,如下所示:

<input-component
    [type]="'text'"
    [id]="'streetName'"
    [label]="'Street'"
    [formControl]="'street'"
    [cssClasses]="'form-control width-100'"
    [withErrors]="true"
    [error]="formErrors['street']"
    [controls]="addressDataForm.controls['street']"
    ngDefaultControl>
</input-component>
  

TypeError:无法在字符串'street'上创建属性'validator'

[formControl]="'street'"的{​​{1}}属性更改为input-component

应该解决这个问题。