表单反应自定义组件

时间:2018-03-21 15:06:49

标签: angular

我有一段代码,想把它变成一个组件

<div class="form-group">
  <label class="form-control-label" for="email"> EMAIL: <span class="star">*</span></label>
  <input class="form-control" type="email" id="email" formControlName="email"/>
  <app-show-errors [control]="cliente.controls.email"></app-show-errors>
</div>

组件输入文本

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

@Component({
    selector: 'app-input-text',
    template: `
        <div class="form-group">
            <label class="form-control-label" for="{{name}}"> NOME: <span
                    class="star" *ngIf="control.errors?.required">*</span></label>
            <input type="text" class="form-control" formControlName="{{control}}" id="{{name}}" />
            <app-show-errors [control]="cliente.controls.email"></app-show-errors>
        </div>
    `
})
export class InputTextComponent {
    @Input() private nome: string;
    @Input() private control: AbstractControlDirective | AbstractControl;
}

组件show-erros

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

@Component({
    selector: 'app-show-errors',
    template: `
        <small *ngIf="shouldShowErrors()" class="text-danger">
            <span *ngFor="let error of listOfErrors() | slice:0:1">{{error}}</span>
        </small>
    `
})
export class ShowErrorsComponent {

    private static readonly errorMessages = {
        'required': () => 'Este campo é requerido.',
        'email': () => 'Por favor, forneça um endereço de email válido.',
        'min': (params) => 'Por favor, forneça um valor maior ou igual a ' + params.requiredMin + '.',
        'minlength': (params) => 'Por favor, forneça ao menos ' + params.requiredLength + ' caracteres. ',
        'max': (params) => 'Por favor, forneça um valor menor ou igual a ' + params.requiredMax + '.',
        'maxlength': (params) => 'Por favor, forneça não mais que ' + params.requiredLength + ' caracteres.',
        'pattern': (params) => 'O formato fornecido é inválido. ' + params.requiredPattern
    };

    @Input() private control: AbstractControlDirective | AbstractControl;

    shouldShowErrors(): boolean {
        return this.control &&
            this.control.errors &&
            (this.control.dirty || this.control.touched);
    }

    listOfErrors(): string[] {
        return Object.keys(this.control.errors)
            .map(field => this.getMessage(field, this.control.errors[field]));
    }

    private getMessage(type: string, params: any) {
        return ShowErrorsComponent.errorMessages[type](params);
    }

}

经过修改后必须采用这种方式

我无法将变量传递给app-input-text

我遇到的另一个问题是* ngIf =“control.errors?.required”仅在必填字段无效时才会出现,只要有一个分配给Validators.required

,就会延迟显示
this.cliente = this.fb.group({
  fisica: this.fb.group({
                nome: [null, [Validators.required, Validators.maxLength(50)]],
  })
 });

1 个答案:

答案 0 :(得分:1)

<label class="form-control-label" for="{{name}}"> NOME: <span

你的姓名&#34;如

@Input() private nome: string;