你好StackOverflow社区!

我正在用Angular + Node开发一个应用程序,我遇到了一个关于使用Material Angular的表单和验证器的大问题.

目前,我遇到了无法识别输入的HTML组件,我不知道我错过了什么.

我有这个代码:

contact.component.html:

<mat-card>
<mat-card-header>
    <mat-card-title>Formulario de contacto</mat-card-title>
    <mat-card-subtitle>Ponte en contacto conmigo</mat-card-subtitle>
</mat-card-header>
<form [formGroup]="contactForm">
    <mat-card-content>
        <mat-form-field>
            <mat-label>Nombre y apellidos</mat-label>
            <input matInput [formGroup]="contactForm" [formControl]="nameFormControl" required name="name" maxlength="128" autocomplete="off" autofocus>
            @if (nameFormControl.hasError('required') || nameFormControl.hasError('pattern')) {
                <mat-error>Por favor, rellena este campo</mat-error>
            }
        </mat-form-field>
    </mat-card-content>
    <mat-card-content>
        <mat-form-field>
            <mat-label>Correo electrónico</mat-label>
            <input matInput [formControl]="emailFormControl" required name="email" maxlength="128" autocomplete="off">
            @if (emailFormControl.hasError('required')) {
                <mat-error>Por favor, rellena este campo</mat-error>
            }
            @else if (emailFormControl.hasError('email')) {
                <mat-error>Debes introducir una dirección de correo electrónico válida</mat-error>
            }
            @else if (emailFormControl.hasError('pattern')) {
                <mat-error>Debes introducir una dirección de correo electrónico válida</mat-error>
            }
        </mat-form-field>
    </mat-card-content>
    <mat-card-content>
        <mat-form-field>
            <mat-label>Mensaje</mat-label>
            <textarea #contactBody matInput [formControl]="bodyFormControl" name="body" maxlength="1024" autocomplete="off"></textarea>
            <mat-hint align="end">{{ contactBody.value.length }} / 1024</mat-hint>
            @if (bodyFormControl.hasError('required') || bodyFormControl.hasError('pattern')) {
                <mat-error>Por favor, rellena este campo</mat-error>
            }
        </mat-form-field>
    </mat-card-content>
</form>
<button mat-raised-button color="primary" (click)="saveMessage()">Enviar formulario</button>

contact.component.ts:

import { Component, OnInit } from '@angular/core';
import { AbstractControl, ReactiveFormsModule, FormBuilder, FormControl, FormGroup, FormGroupDirective, NgForm, Validators } from '@angular/forms';
import { AppService } from './../app.service';
import { MatSnackBar } from '@angular/material/snack-bar';
import { ErrorStateMatcher } from '@angular/material/core';


@Component({
  selector: 'app-contact',
  templateUrl: './contact.component.html',
  styleUrl: './contact.component.scss'
})
export class ContactComponent implements ErrorStateMatcher {

  contactForm: FormGroup = new FormGroup({
    nameFormControl: new FormControl(''),
    emailFormControl: new FormControl(''),
    bodyFormControl: new FormControl(''),
  })

  constructor(private appService: AppService, private formBuilder: FormBuilder, private _snackBar: MatSnackBar) {}

  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    const isSubmitted = form && form.submitted;
    return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));
  }

  ngOnInit(): void {
    this.contactForm = this.formBuilder.group(
      {
        nameFormControl: [
          '',
          [
            Validators.required,
            Validators.pattern(/[\S]/)
          ]
        ], emailFormControl: [
          '',
          [
            Validators.required,
            Validators.email,
            Validators.pattern("^([a-zA-Z0-9-._]+)@([A-Za-z-]+)\.([a-z]{2,3}(.[a-z]{2,3})?)$")
          ]
        ], bodyFormControl: [
          '',
          [
            Validators.required,
            Validators.pattern(/[\S]/g)
          ]
        ]
      },
    );
  }
}

问题出在表格contactForm下的nameFormControlemailFormControlbodyFormControl号表格上.

你们能帮我解释一下这个话题吗?

非常感谢!

推荐答案

FormGroup issue

不应在表单域上设置[formGroup],[formControl]应为formControlName

<!-- Incorrect -->
<input matInput [formGroup]="contactForm" [formControl]="nameFormControl"

<!-- Correct -->
<input matInput formControlName="nameFormControl"

The @IF issue

不能直接访问该控件 您需要像这样使用FormGroup

@if (contactForm.controls.emailFormControl.hasError('required'))

Html相关问答推荐

简化指标与Delta保持一致

CSS Flex行之间的空间很大

如何通过将项目包裹在迪夫中来保持最右列的对齐方式来对齐项目?

如何正确使用counter()、counter—increment()和counter—reset()嵌套标题?

如何获得一个背景图像,不是模糊的内部容器,但模糊的外部'

如何让QML`Text`元素内的链接在悬停时显示鼠标指针?

在css嵌套 Select 器中,尾随的`&;‘是什么意思?

如何影响flex项目中的flex-gap收缩顺序和文本换行顺序?

CSS Grid:使网格行填充屏幕,将下一行推离屏幕

当文本添加到元素中时,将元素拉到页面上

在TWebLabel标题中设置换行符/换行符的方法?

如何在css中在span中绘制圆弧?

是否可以制作响应式 CSS 剪辑路径?

如何检测输入字段是否没有必填且没有占位符?

第 117 行的块标记无效:endblock,应为empty或endfor.您是否忘记注册或加载此标签?

将组件移动到页面底部 Angular

表单中如何分别禁用/启用多个提交按钮?

如何使用 html 和 css 为卡片创建此背景框架

我正在创建一个 django 审查系统.我认为我的 HTML 是错误的

如何在 about:blank 网站上设置页面标题