【问题标题】:Disabling a Submit Button with Angular 2+ Template-Driven-Form and a child component?使用 Angular 2+ 模板驱动表单和子组件禁用提交按钮?
【发布时间】:2019-03-08 21:26:21
【问题描述】:

在 Angular 2+ 中使用模板驱动的表单,我想利用表单中的子组件来更轻松地对表单元素进行单元测试。话虽如此,我希望能够使用模板引用变量(即)button [disabled]="!myForm.form.valid" 禁用提交按钮。我知道应该将某些内容从父表单传递到子组件,但我无法弄清楚那是什么,或者应该使用的语法。

使用 Stackblitz 示例,如果输入验证器(在此示例中特别是 minlength)位于表单的子组件中,我将如何禁用提交按钮?

Stackblitz 示例https://stackblitz.com/edit/angular-zzeton

我查看了以下链接,但它们与真正的输入控制自定义与访问模板引用变量相比更多:

How to add validation in template driven form from component in angular 6 https://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html#demos

【问题讨论】:

    标签: angular


    【解决方案1】:

    声明控制容器

    @Component({
      selector: 'my-hero-name',
      templateUrl: './app.hero-name.html',
      viewProviders: [ { provide: ControlContainer, useExisting: NgForm } ]
    })
    export class HeroNameComponent {
      @Input() hero: Hero;
    }
    
    export class Hero {
      constructor(public name: string) { }
    }
    

    分叉示例:https://stackblitz.com/edit/angular-vmqm8h 参考:https://medium.com/@a.yurich.zuev/angular-nested-template-driven-form-4a3de2042475

    【讨论】:

    • 哇 - 非常简单,谢谢 - 我读过那篇文章,但从未建立联系
    猜你喜欢
    • 2020-09-06
    • 1970-01-01
    • 2017-05-31
    • 1970-01-01
    • 2017-01-30
    • 1970-01-01
    • 2017-06-27
    • 1970-01-01
    • 2015-06-24
    相关资源
    最近更新 更多