【问题标题】:Reuse individual Angular 5 reactive form elements重用单个 Angular 5 反应式表单元素
【发布时间】:2018-05-31 06:27:32
【问题描述】:

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

有没有办法使用 Angular 5 响应式表单来做到这一点,只使用一个文件并包含模板和所有验证?我可以分两部分看到如何做到这一点,其中我将有一个包含表单元素 HTML、验证消息等的组件,但是您还需要在完整表单的组件中创建 FormControl 并为其提供默认值和验证。

也许这是非常常见的,我只是没有正确搜索它,但如果有人能指出我的任何模式、教程或帮助,我将不胜感激,因为我觉得这是我在表单中缺少的最后一块.谢谢!

【问题讨论】:

    标签: forms angular5 reactive


    【解决方案1】:

    如果其他人遇到这个问题,我能找到的最佳答案(并且至少被许多其他开发人员使用,即使不是最佳实践)是在父“主表单”中创建一个 FormGroup组件,然后创建一个新的 FormControl 并将其附加到该 FormGroup。例如,这里是可重用表单控件的组件:

    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;
    }
    
    }
    

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

    <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>
    

    这是父表单的组件(它已经包含了我正在编写的教程中的一些内置表单元素,并且只有一个可重复使用的表单元素组件):

    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} {
      ...
    }
    }
    

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

    <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>
            ...
    

    【讨论】:

      猜你喜欢
      • 2019-06-24
      • 1970-01-01
      • 2021-01-12
      • 2018-02-01
      • 1970-01-01
      • 2018-07-22
      • 2018-05-24
      • 2019-05-18
      • 2019-01-15
      相关资源
      最近更新 更多