使用自定义输入激活表单

时间:2018-04-11 19:35:06

标签: angular angular-components angular-reactive-forms angular-validation

我想使用自定义输入组件创建表单,并且遇到以下问题。

  

错误:没有名称为'nome'Stack的表单控件的值访问器   跟踪:   _throwError @的WebPack内部:///./node_modules/@angular/forms/esm5/forms.js:2510:11   setUpControl @的WebPack内部:///./node_modules/@angular/forms/esm5/forms.js:2380:9   FormGroupDirective.prototype.addControl@webpack-internal:///./node_modules/@angular/forms/esm5/forms.js:6736:9   FormControlName.prototype._setUpControl@webpack-internal:///./node_modules/@angular/forms/esm5/forms.js:7386:45   FormControlName.prototype.ngOnChanges@webpack-internal:///./node_modules/@angular/forms/esm5/forms.js:7299:13

这是我的输入组件:

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

@Component({
  selector: 'app-pf-input-text',
  templateUrl: './pf-input-text.component.html',
  styleUrls: ['./pf-input-text.component.scss']
})
export class PfInputTextComponent implements OnInit {

  @Input() id: string;
  @Input() name: string;
  @Input() value: string;
  @Input() placeholder: string;
  @Input() formControlName: any;

  //falta trim

  @Input() maxlength: string;
  @Input() minlength: string;

  @Input() disabled: boolean;
  @Input() required: boolean;

  constructor() { }

  ngOnInit() {
  }
  }

}

HTML:

<div class="input-group">
  <input 
      type="text" class="form-control">
</div>

我试图按如下方式使用它:

<form [formGroup]="empresaForm">
  <div class="form-row">

    <app-pf-input-text formControlName="nome"></app-pf-input-text>

  </div>
</form>

这是我的表格:

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

import { FormArray, FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';

import { Empresa } from '../empresa.model';

@Component({
  selector: 'app-empresa-cadastro',
  templateUrl: './empresa-cadastro.component.html',
  styleUrls: ['./empresa-cadastro.component.css']
})
export class EmpresaCadastroComponent implements OnInit {

  empresaForm: FormGroup;

  nomeControl: FormControl;

  constructor(private fb: FormBuilder) {}

  createForm() {
    this.nomeControl = new FormControl('', [
      Validators.required,
      Validators.minLength(3),
      Validators.maxLength(10)
    ]);
  }

  createFormControl() {
    console.log('Criando FormControl');
  }

  onSubmit() {
    const empresa = this.empresaForm.value as Empresa;
    console.log('Empresa: ', empresa);
  }

  limpar() {
    this.empresaForm.reset();
  }

  ngOnInit() {
    this.createForm();
  }

}

我不知道如何通过我的自定义输入将formControlName指令传递给输入。

0 个答案:

没有答案