重复使用单个Angular 5反应性表单元素 [英] Reuse individual Angular 5 reactive form elements

查看:62
本文介绍了重复使用单个Angular 5反应性表单元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍在学习Angular 5,并已开始使用反应式"表单模型.但是,几乎我可以找到的所有示例和教程都可以在一个模板中创建整个表单.通常,在AngularJS 1.x中,我们将每个字段存储在自己的指令中,然后将它们连接在一起以创建一个表单以减少重复.

I am still learning Angular 5 and have started working with the "reactive" form model. However, almost every example and tutorial I can find has you creating the entire form in one template. Normally in AngularJS 1.x, we would store each field in its own directive and then wire them together to create a form to cut down on duplication.

是否有一种方法可以仅使用一个文件并包含模板和所有验证,来对Angular 5反应式表单进行此操作?我可以分为两部分来了解如何做到这一点,我将拥有一个包含表单元素HTML,验证消息等的组件,但是您还需要在完整表单的组件中创建FormControl并将其默认值设置为验证.

Is there a way to do this with Angular 5 reactive forms using only one file and having the template and all validations included? I can see how to do it in two pieces, where I would have a component that contains the form element HTML, validation messages, etc. but then you also need to create the FormControl in the full form's component and give it its default value and validations.

也许这是非常普遍的,我只是没有正确地寻找它,但是如果有人可以将我引向任何模式,教程或帮助,我将不胜感激,因为我认为这是我所缺少的表格的最后一部分.谢谢!

Maybe this is extremely common and I am just not searching for it correctly, but if anyone can point me towards any patterns, tutorials or help I would greatly appreciate it as I feel it is the last piece I am missing for my forms. Thank you!

推荐答案

万一其他人遇到这个问题,我就能找到最好的答案(即使不是最好的,它也至少会被许多其他开发人员使用.实践)是在父级主窗体"组件中创建一个FormGroup,然后创建一个新的FormControl并将其附加到该FormGroup.例如,这是可重复使用的表单控件的组件:

In case anyone else comes across this, the best answer I could find (and which is at least used by many other devs out there, even if not a best practice) is to create a FormGroup in the parent "main form" component and then create and attach a new FormControl to that FormGroup. For example, here is the component for the re-usable form control:

import {Component, OnInit, Input} from '@angular/core';
import {FormControl, FormGroup, Validators} from '@angular/forms';

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

 @Input() isFormSubmitted: boolean;
 @Input() projectForm: FormGroup;

 constructor() {
 }

 ngOnInit() {
 this.projectForm.addControl('projectLength', new FormControl(0, [Validators.required, this.hasCorrectLength]));
 }

 hasCorrectLength(control: FormControl): {[s: string]: boolean} {
   const length: number = control.value;
  if (length < 2 || length > 10) {
    return { 'incorrectLength' : true };
  }
  return null;
}

}

这是该表单元素组件的模板:

Here is the template for that form element component:

<div class="form-group" [formGroup]="projectForm">
<label for="project-length">project length</label>
<input
  class="form-control"
  type="number"
  id="project-length"
  placeholder="Enter project length"
  formControlName="projectLength"
/>
<span class="help-block" 
  *ngIf="!projectForm.controls['projectLength'].valid && (projectForm.controls['projectLength'].touched || isFormSubmitted)">
    please enter a project length between 2 and 9
</span>

这是父表单的组成部分(已经有我正在研究的教程中的一些内置表单元素,并且只有一个可重用的表单元素组件):

Here is the component of the parent form (which already has some built-in form elements from a tutorial I was working on, and only one re-usable form element component):

import { Component, OnInit } from '@angular/core';
import {FormControl, FormGroup, Validators} from '@angular/forms';
import { Status} from '../shared/Status';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  projectForm: FormGroup;
  statuses: Array<Status> = [
    {id: 1, name: 'Critical'},
    {id: 2, name: 'Stable'},
    {id: 3, name: 'Finished'}
  ];
  formSubmitted: boolean = false;

  ngOnInit() {
    this.projectForm = new FormGroup({
      namey: new FormControl(null, [Validators.required, this.cannotBeTest1]),
      email: new FormControl(null, [Validators.required, Validators.email]),
      status: new FormControl('1')
    });
  }

  onSubmit() {
    console.log(this.projectForm);

    this.formSubmitted = true;
    if (this.projectForm.valid) {
    console.log('Form data:');
    console.log(this.projectForm);
  }
}
cannotBeTest1(control: FormControl): {[s: string]: boolean} {
  ...
}
}

这是主要表单组件模板的重要部分:

And here are the important parts of the template for the main form component:

<div class="container">
  <div class="row">
    <div class="col-xs-12 col-sm-10 col-md-8 col-sm-offset-1 col-md-offset-2">
      <form class="ui form-vertical" [formGroup]="projectForm" (ngSubmit)="onSubmit()">
        ...
        <app-project-length [projectForm]="projectForm" [isFormSubmitted]="formSubmitted"></app-project-length>
        ...

这篇关于重复使用单个Angular 5反应性表单元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆