【问题标题】:FormControl Validators表单控件验证器
【发布时间】:2021-02-10 22:14:12
【问题描述】:

我知道这段代码对我有用:

this.BridgeForm = this.formBuilder.group({
    gateway: ["", [Validators.required, Validators.pattern(this.ipRegex)]],
});

但是,我想更明确地使用属性:

this.BridgeForm = this.formBuilder.group({
    gateway: {
        value: "", disabled: false,
        Validators: [
            Validators.required,
            Validators.pattern(this.ipRegex),
        ]
    },
});

我总是在控制台中遇到错误,如下所示:

ERROR 错误:MaskedTextBox 组件仅支持字符串值。

问题在于验证器属性。我无法从documentation 中弄清楚如何使用它。

【问题讨论】:

    标签: angular typescript forms validation


    【解决方案1】:

    您缺少属性值的 FormControl。顶部对象(表单)将创建 FormGroup 的一个实例,每个属性都需要一个 FormControl,您可以在其中定义必要的验证器、禁用等

    以下是更新后的语法以适用于您的示例:

    this.bridgeForm = this.formBuilder.group({
      gateway: new FormControl({ value: "", disabled: false }, [
        Validators.required,
        Validators.pattern(this.ipRegex)
      ])
    });
    

    演示: https://stackblitz.com/edit/angular-ivy-swbfa3?file=src/app/app.component.ts

    【讨论】:

    • 我明白了。我必须明确调用new FormControl (),即使它是FormBuilder。谢谢。
    • 你需要为你想要“控制”的每个属性都这样做
    猜你喜欢
    • 2022-12-22
    • 1970-01-01
    • 2018-02-04
    • 2017-09-01
    • 2019-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多