首页 文章

使用组件进行角度2表单级别验证

提问于
浏览
8

在Angular 2中,如何在自定义组件中添加输入控件,该组件将绑定到父组件中的表单控件容器? (以下代码简化了BREVITY)

例如,我有一个表单组件(请注意按钮禁用绑定)

@Component{
selector:'my-form',
template:'
<form [ng-form-model]="myForm">
    <my-special-input></my-special-input>
</form>
<button [disabled]="!myForm.valid">
'
}

现在在我的特殊输入组件中,我想

@component{
 selector:'my-special-input'
 template:'
    <input ng-control='name' required>
}'

ng-control = 'name'生成错误 "No provider for ControlContainer!" 我搜索了解决方案,但未找到任何允许父表单控件容器验证的解决方案 .

我认为创建添加到表单控件容器的自定义可重用输入组件将是Angular 2中的常见方案 .

我无法在那里进行映像,无法将自定义组件中的输入添加到父表单组件中,以便启用表单级别验证 .

2 回答

  • 6

    不确定这是否适合您的方案,但我认为它有效 .

    您可以在父元素上创建 Control 并将其作为 @Input 传递给子元素 . 然后,孩子可以将其用作表单元素的控件 .

    例如(plunk):

    @Component({
      selector:'my-special-input'
      template:`
            <input type="text" [ngFormControl]='nameControl' > 
        `
    })
    export class specialInputComponent implements OnInit{
      @Input() nameControl;
    }
    
    @Component({
      selector:'my-form',
      template:`
        <form [ngFormModel]="myForm" >
           <my-special-input [nameControl]="nameControl"></my-special-input>
        </form>
        <button [disabled]="!myForm.valid">Submit</button>
        `,
        directives: [specialInputComponent]
    })
    export class formComponent{
        nameControl:Control;
        myForm: ControlGroup;
    
        constructor(){
            this.nameControl = new Control("", Validators.required );
            this.myForm = new ControlGroup({special: this.nameControl});
            }
    }
    

    您可能还可以将 ControlGroup 传递给子进程并让子进程添加 addControl() 但您可能必须处理更新周期变得有点混乱 .

  • -1

    使用Angular进行表单验证将验证与组件相结合 .

    这导致围绕验证的业务逻辑分散在组件中的整个应用程序中 .

    很多时候最好创建一个基于TypeScript的 re-usable validation service .

    • 这允许业务逻辑集中在一个地方 .

    • 您可以通过单元测试服务来对此业务逻辑进行单元测试 .

    这个 demo Angular 6 CLI app 告诉你如何做到这一点 .

    https://github.com/VeritasSoftware/ts-validator-app-angular6

    从设计考虑,您可能会发现这很有用 .

相关问题