Angular响应式表单 - 无法在提交时设置自定义验证消息的文本字段
创始人
2024-10-30 05:30:25
0

在Angular响应式表单中,如果想在提交表单时设置自定义验证消息的文本字段,可以通过在表单控件上使用setErrors()方法来实现。

以下是一个示例,演示了如何设置自定义验证消息的文本字段:

HTML模板:

Name is required.
Custom error message.

组件代码:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css']
})
export class MyComponentComponent implements OnInit {
  myForm: FormGroup;

  constructor(private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.myForm = this.formBuilder.group({
      name: ['', [Validators.required]]
    });
  }

  onSubmit() {
    if (this.myForm.valid) {
      // Perform form submission
    } else {
      // Set custom error message
      this.myForm.get('name').setErrors({ customError: true });
    }
  }
}

在上述示例中,我们使用了一个自定义验证器customError来表示自定义错误消息。当表单提交时,如果表单无效,则会调用onSubmit()方法。在该方法中,我们使用setErrors()方法将customError设置为表单控件的错误。然后,在模板中,我们使用*ngIf指令来根据表单控件的错误状态显示相应的错误消息。

请注意,setErrors()方法接受一个对象作为参数,该对象的属性名表示错误类型,属性值表示错误值。在示例中,我们将customError设置为true,但您可以根据需要设置任何值。

希望这可以帮助到你!

相关内容

热门资讯

透视好友房!hh poker辅... 透视好友房!hh poker辅助器先试用,hhpoker俱乐部是干嘛的,实用技巧(有挂技巧)1、hh...
透视透视!hhpoker软件可... 透视透视!hhpoker软件可以玩吗,hhpkoer辅助器视频,第三方教程(有挂详情)透视透视!hh...
透视教学!hhpoker有辅助... 透视教学!hhpoker有辅助吗,德州hhpoker脚本,安装教程(有挂技巧)亲,关键说明,德州hh...
透视系统!hh poker软件... 透视系统!hh poker软件,hhpoker有后台操作吗,必胜教程(有挂技巧)进入游戏-大厅左侧-...
透视存在!hhpoker软件安... 透视存在!hhpoker软件安装包,hhpoker有作弊的吗,系统教程(有挂技巧)1、该软件可以轻松...
透视安装!hhpoker辅助器... 透视安装!hhpoker辅助器视频,德州hhpoker是真的吗,插件教程(有挂教程)德州hhpoke...
透视实锤!hhpoker是内部... 透视实锤!hhpoker是内部控制吗,hhpoker软件靠谱吗,攻略方法(有挂细节)1、完成hhpo...
透视辅助!hhpoker透视脚... 透视辅助!hhpoker透视脚本,hhpoker哪个俱乐部靠谱,安装教程(有挂攻略)运hhpoker...
透视代打!hhpoker有辅助... 透视代打!hhpoker有辅助吗,hhpoker真能买到挂吗,解说技巧(有挂方法)亲,关键说明,hh...
透视透视挂!hhpoker怎么... 透视透视挂!hhpoker怎么开透视,hhpoker辅助挂下载,大神讲解(有挂工具);1、实时hhp...