typescript – 如何解决使用大量自定义组件创建复杂表单的问题?

假设我从angular2 app生成的html看起来像这样:
<app>
<form [formGroup]="myForm" (ngSubmit)="onSubmit(myForm.value)">
<panel-component>
    <mid-component>
        <inner-component-with-inputs>
            <input/>
        <inner-component-with-inputs>
    <mid-component>
</panel-component>
<panel-component>
    <mid-component>
        <inner-component-with-inputs>
            <input/>
        <inner-component-with-inputs>
    <mid-component>
</panel-component>

<!-- many many many fields -->

<button type="submit">Submit</button>
</form>
</app>

如何设置外部< form>以这种方式我可以在提交时验证所有内部输入?我是否必须通过@Input()将myForm从面板组件一直传递到内部组件与输入?或者还有其他方式吗?

在我的应用程序中,我有非常大的形式,有多个面板,子面板,标签,模态等.我需要能够在提交时立即验证它.

互联网上的所有教程和资源仅涉及跨越一个组件/模板的表单.

解决方法

当涉及父/子关系时,您将在整个Angular源代码中看到的常见模式是父类型,将自身添加为自身的提供者.这样做是允许子组件注入父组件.由于 hierarchical DI,在组件树中只会有一个父组件的实例.下面是一个可能看起来像的例子
export abstract class FormControlContainer {
  abstract addControl(name: string,control: FormControl): void;
  abstract removeControl(name: string): void;
}

export const formGroupContainerProvider: any = {
  provide: FormControlContainer,useExisting: forwardRef(() => NestedFormComponentsComponent)
};

@Component({
  selector: 'nested-form-components',template: `
    ...
  `,directives: [REACTIVE_FORM_DIRECTIVES,ChildComponent],providers: [formGroupContainerProvider]
})
export class ParentComponent implements FormControlContainer {
  form: FormGroup = new FormGroup({});

  addControl(name: string,control: FormControl) {
    this.form.addControl(name,control);
  }

  removeControl(name: string) {
    this.form.removeControl(name);
  }
}

一些说明:

>我们使用接口/抽象父(FormControlContainer)有几个原因

>它将ParentComponent与ChildComponent分离.孩子不需要知道关于特定ParentComponent的任何信息.所有它知道的是FormControlContainer和合同.
>我们只通过接口契约在ParentComponent上公开需要的方法.

>我们只将ParentComponent宣传为FormControlContainer,因此后者是我们将注入的内容.
>我们以formControlContainerProvider的形式创建提供程序,然后将该提供程序添加到ParentComponent.由于分层DI,现在所有孩子都可以访问父母.
>如果您不熟悉forwardRef,this is a great article

现在,你可以做孩子

@Component({
  selector: 'child-component',directives: [REACTIVE_FORM_DIRECTIVES]
})
export class ChildComponent implements OnDestroy {
  firstName: FormControl;
  lastName: FormControl;

  constructor(private _parent: FormControlContainer) {
    this.firstName = new FormControl('',Validators.required);
    this.lastName = new FormControl('',Validators.required);
    this._parent.addControl('firstName',this.firstName);
    this._parent.addControl('lastName',this.lastName);
  }

  ngOnDestroy() {
    this._parent.removeControl('firstName');
    this._parent.removeControl('lastName');
  }
}

IMO,这比通过@Inputs传递FormGroup要好得多.如前所述,这是Angular源代码中的常见设计,因此我认为可以肯定地说这是一种可接受的模式.

如果要使子组件更可重用,可以创建构造函数参数@Optional().

以下是我用来测试上述例子的完整资料

import {
  Component,OnInit,ViewChildren,QueryList,OnDestroy,forwardRef,Injector
} from '@angular/core';
import {
  FormControl,FormGroup,ControlContainer,Validators,FormGroupDirective,REACTIVE_FORM_DIRECTIVES
} from '@angular/forms';


export abstract class FormControlContainer {
  abstract addControl(name: string,template: `
    <form [formGroup]="form">
      <child-component></child-component>
      <div>
        <button type="button" (click)="onSubmit()">Submit</button>
      </div>
    </form>
  `,forwardRef(() => ChildComponent)],providers: [formGroupContainerProvider]
})
export class NestedFormComponentsComponent implements FormControlContainer {

  form = new FormGroup({});

  onSubmit(e) {
    if (!this.form.valid) {
      console.log('form is INVALID!')
      if (this.form.hasError('required',['firstName'])) {
        console.log('First name is required.');
      }
      if (this.form.hasError('required',['lastName'])) {
        console.log('Last name is required.');
      }
    } else {
      console.log('form is VALID!');
    }
  }

  addControl(name: string,control: FormControl): void {
    this.form.addControl(name,control);
  }

  removeControl(name: string): void {
    this.form.removeControl(name);
  }
}

@Component({
  selector: 'child-component',template: `
    <div>
      <label for="firstName">First name:</label>
      <input id="firstName" [formControl]="firstName" type="text"/>
    </div>
    <div>
      <label for="lastName">Last name:</label>
      <input id="lastName" [formControl]="lastName" type="text"/>
    </div>
  `,this.lastName);
  }


  ngOnDestroy() {
    this._parent.removeControl('firstName');
    this._parent.removeControl('lastName');
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


我最大的一个关于TypeScript的问题是,它将原型的所有方法(无论访问修饰符)编译.例classExample{publicgetString():string{return"HelloWorld";}privategetNumber():number{return123;}}众所周知,访问修饰符仅在编译时检
我对React很新,我正在尝试理解子组件之间相互通信的简洁方法.在一个简单的组件中,我知道我可以使用props将数据传递给子节点,并让子节点的回调将数据传递回父组件.在稍微复杂的情况下,当我在父组件中有多个子组件时,子组件之间的通信会有点混乱.我不确定我应该为同级别的儿童组
我有一个非常简单的表单,我将用户电子邮件存储在组件的状态,并使用onChange函数更新状态.有一个奇怪的事情发生在我的onChange函数用函数更新状态时,我在键入时在控制台中得到两个错误.但是,如果我使用对象更新状态,则不会出现错误.我相信用函数更新是推荐的方法,所以我很想知道为
我发现接口非常有用,但由于内存问题我需要开始优化我的应用程序,我意识到我并不真正了解它们在内部如何工作.说我有interfaceFoo{bar:number}我用这种类型实例化一些变量:letx:Foo={bar:2}Q1:这会创建一个新对象吗?现在,假设我想改变bar的值.我这样做有两种
我得到了一个json响应并将其存储在mongodb中,但是我不需要的字段也进入了数据库,无论如何要剥离不道德的字段?interfaceTest{name:string};consttemp:Test=JSON.parse('{"name":"someName","age":20}')asTest;console.log(temp);输出:{name:'someName
我试图使用loadsh从以下数组中获取唯一类别,[{"listingId":"p106a904a-b8c6-4d2d-a364-0d21e3505010","section":"section1","category":"VIPPASS","type":"paper","availableTi
我有以下测试用例:it("shouldpassthetest",asyncfunction(done){awaitasyncFunction();true.should.eq(true);done();});运行它断言:Error:Resolutionmethodisoverspecified.SpecifyacallbackorreturnaPromise;n
我正在一个有角度的2cli项目中工作,我必须创建一个插件的定义,因为它不存在它的类型.这个插件取决于已经自己输入的主库,它可以工作.无论如何,我有两个文件主要的一个图书馆类型文件AexportclassAextendsB{constructor(...);methodX():void;}我需要为我的
我有三元操作的问题:leta=undefined?"Defined!":"DefinitelyUndefined",b=abc?"Defined!":"DefinitelyUndefined",//ReferenceErrorc=(abc!==undefined)?"Defined!":"DefinitelyUndefin
下面的代码片段是30秒的代码网站.这是一个初学者的例子,令人尴尬地让我难过.为什么这样:constcurrentURL=()=>window.location.href;什么时候可以这样做?constcurrentURL=window.location.href;解决方法:第一个将currentURL设置为一个求值为window.location.href的
我是TypeScript和AngularJS的新手,我正在尝试从我的API转换日期,例如:"8/22/2015"…到ISO日期.将日期正确反序列化为Date类型的TypeScript属性.但是,当我尝试以下命令时(在typescript中,this.dateDisplay的类型为string)this.dateDisplay=formats.dateTimeValue.toISOString
我的名为myEmployees的数组中有5个名字,但是当我运行代码时,它只打印出其中的3个.我相信这种情况正在发生,因为脚本中的for循环覆盖了它在HTML文档中编写的前一行.我怎样才能解决这个问题?YearlyBulletinBoardAnnouncements!CongratulationstoTaylor,youhavebeenheref
我看到有一种方法可以在摩纳哥编辑器中设置scrolltop.如何滚动到特定行而不是特定像素?解决方法:如在文档中:https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.icodeeditor.html滚动到顶部,在px中:editor.setScrollPosition({scrollTop:0});滚动到特定
在从同一个类继承的一个数组中收集各种不同的对象时,如何在TypeScript中设置一个优等的类,以便TypeScript不显示错误?我正在尝试这样:interfaceIVehicle{modelName:string}interfaceICarextendsIVehicle{numberOfDoors:number,isDropTop:boolean}inte
什么是TypescriptTypeScript是一种由微软开发的自由和开源的编程语言,它是JavaScript的一个超集,扩展了JavaScript的语法。作者是安德斯大爷,Delphi、C#之父(你大爷永远是你大爷)。把弱类型语言改成了强类型语言,拥有了静态类型安全检查,IDE智能提示和追踪,代码重构简单、可读性
0.系列文章1.使用Typescript重构axios(一)——写在最前面2.使用Typescript重构axios(二)——项目起手,跑通流程3.使用Typescript重构axios(三)——实现基础功能:处理get请求url参数4.使用Typescript重构axios(四)——实现基础功能:处理post请求参数5.使用Typescript重构axios(五
1.1Typescript介绍1.TypeScript是由微软开发的一款开源的编程语言,像后端java、C#这样的面向对象语言可以让js开发大型企业项目。2.TypeScript是Javascript的超级,遵循最新的ES6、Es5规范(相当于包含了es6、es5的语法)。TypeScript扩展了JavaScript的语法。3.最新的Vu
0.系列文章1.使用Typescript重构axios(一)——写在最前面2.使用Typescript重构axios(二)——项目起手,跑通流程3.使用Typescript重构axios(三)——实现基础功能:处理get请求url参数4.使用Typescript重构axios(四)——实现基础功能:处理post请求参数5.使用Typescript重构axios(
webpack.config.jsconstpath=require('path');constCopyWebpackPlugin=require('copy-webpack-plugin');constExtractTextPlugin=require('extract-text-webpack-plugin');const{CleanWebpackPlugin}=require('clean-webpac
我在这篇ECMAScriptpage上读到“class”是JavaScript的一部分.在这个关于TypeScript的页面上,我看到’class’也可以在Typescript中找到.我的问题是,开发未来JavaScript应用程序的正确方法是利用(a)JavaScript中的面向对象功能以及EMACScript7.0中可用的功能或(b)使用TypeScript