Mat错误在Angular以下代码中不起作用?

时间:2020-06-07 20:26:32

标签: html angular angular-forms

我想知道为什么Mat错误在Angular以下代码中不起作用?

<div class="form-group">
  <mat-form-field class="row-styling">
    <mat-label for="aplctnName">
      Application Name <span class="text-danger font-weight-bold">*</span>
    </mat-label>
    <input
      matInput
      type="text"
      placeholder="Enter Application Name here"
      alphabetOnly
      maxlength="40"
      formControlName="aplctnName"
      [ngClass]="{ 'is-invalid': submitted && fields.aplctnName.errors }"
    />
    <mat-error *ngIf="fields.aplctnName.errors.required"
      >Application Name is required</mat-error
    >
    error>
  </mat-form-field>
</div>

在下面的代码中,每当我按下下一步按钮时,mat-error都不起作用。

任何人都可以帮助解决此问题吗?

1 个答案:

答案 0 :(得分:1)

您可以检查我的解决方案。

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';

@NgModule({
  imports:      [ BrowserModule, FormsModule, ReactiveFormsModule, MatFormFieldModule, MatInputModule, BrowserAnimationsModule ],
  declarations: [ AppComponent, HelloComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

styles.scss

/* Add application styles & imports to this file! */
@import "@angular/material/prebuilt-themes/deeppurple-amber.css";

app.component.ts

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  form: FormGroup;
  submitted: boolean = false;

  ngOnInit() {
    this.form = new FormGroup({
      aplctnName: new FormControl('', Validators.required)
    });

    console.log(this.form)
  }

  onSubmit(event) {

  }
}

app.component.html

<form [formGroup]="form" (ngSubmit)="onSubmit($event)">
  <div class="form-group">
    <mat-form-field class="row-styling">
      <mat-label for="aplctnName">
        Application Name <span class="text-danger font-weight-bold">*</span>
      </mat-label>
      <input
        matInput
        type="text"
        placeholder="Enter Application Name here"
        alphabetOnly
        maxlength="40"
        formControlName="aplctnName"
        [ngClass]="{ 'is-invalid': submitted && form.get('aplctnName').errors }"
      />
      <mat-error *ngIf="form.get('aplctnName').errors?.required"
        >Application Name is required</mat-error
      >

    </mat-form-field>
    <button type="submit">submit</button>
  </div>
</form>

您可以检查工作demo here

让我知道您是否仍然遇到任何问题。