输入未通过表单

时间:2018-01-24 21:07:55

标签: angular2-template angular2-forms

我创建了一个输入组件,可以在几个表单之间重用它。在其中一个中,它完美地工作,但在另一个中,它不是。

它不会抛出任何错误。我甚至在提交后收到输入值。

  

code.component.html

<div [ngClass]="aplicaCssErro(ag)">
<label for="code">Code</label>
<input id="code" name="code" type="text" class="form-control" [(ngModel)]="value" required #ag="ngModel"
    maxlength="4" minlength="4" (blur)="formatCode(ag)">
<div *ngIf="verificaValidTouched(ag)" class="msgErroText">
    <gce-campo-control-erro [mostrarErro]="ag?.errors?.required" msgErro="the code is required">
    </gce-campo-control-erro>
</div>

  

code.component.ts

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

@Component({
  selector: 'gce-input-code',
  templateUrl: './input-code.component.html',
  styleUrls: ['./input-code.component.scss']
})
export class InputCodeComponent implements OnInit {

  @Input() value: string = "";

  constructor() { }

  ngOnInit() {
  }

//some functions

}
  

form.component.html

问题是表单没有验证它,只是第一个输入。

我认为表单并未将其视为其中一项输入。

<form (ngSubmit)="onSubmitForm2(f)" #f="ngForm">
<div class="row">
  <div class="col-sm-6" [ngClass]="aplicaCssErro(apelido)">
    <label for="apelido">Apelido da conta</label>
    <input id="apelido" name="apelido" type="text" class="form-control" alt="Apelido" [(ngModel)]="conta.apelido" required #apelido="ngModel">
    <div *ngIf="verificaValidTouched(apelido)" class="msgErroText">
      <gce-campo-control-erro [mostrarErro]="apelido?.errors?.required" msgErro="O Apelido é obrigatório.">
      </gce-campo-control-erro>
    </div>
  </div>
</div>
<div class="row">
   <div class="form-group">
      <div class="col-sm-2">
         <gce-input-code name="code" [(ngModel)]="user.code" #code="ngModel" ngDefaultControl></gce-input-code>
       </div>
   </div>
 </div>

 <div class="row">
   <button class="btn btn-default" name="btn2" type="submit" alt="Continuar" [disabled]="!f.valid">Continue</button>
  </div>

任何帮助?

1 个答案:

答案 0 :(得分:0)

如果我理解你的问题。您正在尝试使表单(ngForm)可以验证包含输入的自定义组件(gce-input-code)。

普通表单无法知道组件的内容是什么,因为它是Angular组件。您必须增强code.component.ts以包含所有连接器(ControlValueAccessor,NG_VALUE_ACCESSOR,NG_VALIDATORS)。

查看此博客 https://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html#custom-form-control-considerations

及其plnkr(下面的exerpt代码) https://plnkr.co/edit/6xVdppNQoLcsXGMf7tph?p=info

import { Component, OnInit, forwardRef, Input, OnChanges } from '@angular/core';
    import { FormControl, ControlValueAccessor, NG_VALUE_ACCESSOR, NG_VALIDATORS } 
    from '@angular/forms';


export function createCounterRangeValidator(maxValue, minValue) {
  return (c: FormControl) => {
    let err = {
      rangeError: {
        given: c.value,
        max: maxValue || 10,
        min: minValue || 0
      }
    };

  return (c.value > +maxValue || c.value < +minValue) ? err: null;
  }
}

@Component({
  selector: 'counter-input',
  template: `
    <button (click)="increase()">+</button> {{counterValue}} <button (click)="decrease()">-</button>
  `,
  providers: [
    { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => CounterInputComponent), multi: true },
    { provide: NG_VALIDATORS, useExisting: forwardRef(() => CounterInputComponent), multi: true }
  ]
})
export class CounterInputComponent implements ControlValueAccessor, OnChanges {

  propagateChange:any = () => {};
  validateFn:any = () => {};

  @Input('counterValue') _counterValue = 0;
  @Input() counterRangeMax;
  @Input() counterRangeMin;

  get counterValue() {
    return this._counterValue;
  }

  set counterValue(val) {
    this._counterValue = val;
    this.propagateChange(val);
  }

  ngOnChanges(inputs) {
    if (inputs.counterRangeMax || inputs.counterRangeMin) {
      this.validateFn = createCounterRangeValidator(this.counterRangeMax, this.counterRangeMin);
      this.propagateChange(this.counterValue);
    }
  }

  writeValue(value) {
    if (value) {
      this.counterValue = value;
    }
  }

  registerOnChange(fn) {
    this.propagateChange = fn;
  }

  registerOnTouched() {}

  increase() {
    this.counterValue++;
  }

  decrease() {
    this.counterValue--;
  }

  validate(c: FormControl) {
    return this.validateFn(c);
  }
}