【问题标题】:Disable submit form when form invalid Angular + Material当表单无效Angular + Material时禁用提交表单
【发布时间】:2018-07-20 06:33:24
【问题描述】:

我正在使用 Angular 5.1.1 /Typescript 2.4.2 + Material 5 和 sat-popover 库构建一个表单

尝试在输入无效时禁用提交按钮但没有成功。 我正在使用材料Input validation example

验证有效,我收到一条错误消息,但按钮未被禁用,并且表单已提交空值。我不知道如何在输入无效时使用正确的条件来禁用按钮。 试过了

ng-disabled="!flagForm.valid"

ng-disabled="flagForm.$invalid"

使用时

[disabled]="!flagForm.valid"

我得到'TypeError:无法读取未定义的属性'有效''

它们似乎都不起作用。我错过了什么?这是完整的代码。

   import { Component, Input, Optional, Host } from '@angular/core';
    import { FormControl, FormGroupDirective, NgForm, Validators} from '@angular/forms';
    import { SatPopover } from '@ncstate/sat-popover';
    import { filter } from 'rxjs/operators/filter';
    import { ErrorStateMatcher} from '@angular/material/core';

    /** Error when invalid control is dirty, touched, or submitted. */
    export class MyErrorStateMatcher implements ErrorStateMatcher {
      isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
        const isSubmitted = form && form.submitted;
        return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));
      }
    } 

    @Component({
      selector: 'inline-edit',
      styleUrls: ['inline-edit.component.scss'], 
      template: `
        <form (ngSubmit)="onSubmit()" name="flagForm" novalidate>
          <div class="mat-subheading-2">Submit Your flag</div>

          <mat-form-field>
            <input matInput maxLength="140" name="flag" [(ngModel)]="flag" [formControl]="flagFormControl"
               [errorStateMatcher]="matcher">
            <mat-hint align="end">{{flag?.length || 0}}/140</mat-hint>
            <mat-error *ngIf="flagFormControl.hasError('required')">
              Flag is <strong>required</strong>
            </mat-error>        
          </mat-form-field>

          <div class="actions">
            <button mat-button type="button" color="primary" (click)="onCancel()" class="btn btn-secondary m-btn m-btn--air m-btn--custom">CANCEL</button>
            <button mat-button type="submit" ng-disabled="!flagForm.valid" color="primary" class="btn btn-accent m-btn m-btn--air m-btn--custom">Submit</button>
          </div>
        </form>
      `
    })
    export class InlineEditComponent {

      flagFormControl = new FormControl('', [
        Validators.required
      ]);

      matcher = new MyErrorStateMatcher();

      /** Overrides the flag and provides a reset value when changes are cancelled. */
      @Input()
      get value(): string { return this._value; }
      set value(x: string) {
        this.flag = this._value = x;
      }
      private _value = '';

      /** Form model for the input. */
      flag = '';

      constructor(@Optional() @Host() public popover: SatPopover) { }

      ngOnInit() {
        // subscribe to cancellations and reset form value
        if (this.popover) {
          this.popover.closed.pipe(filter(val => val == null))
            .subscribe(() => this.flag = this.value || '');
        }
      }

      onSubmit() {
        if (this.popover) {
          this.popover.close(this.flag);
        }
      }

      onCancel() {
        if (this.popover) {
          this.popover.close();
        }
      }
    }

【问题讨论】:

  • 我是[disabled]
  • 我也试过了.. 我得到 'TypeError: Cannot read property 'valid' of undefined'

标签: angular typescript angular-material


【解决方案1】:

你的表单没有定义,解决这个问题:

在您的组件中:

flagFormControl: FormGroup = new FormGroup({});

ngOnInit(): void {
// for example
this.flagFormControl= this.formBuilder.group({
      'username': new FormControl('', [Validators.required, Validators.minLength(3)]),
      'email': new FormControl('', [Validators.required, Validators.email]),
      'password': new FormControl('', [Validators.required, Validators.minLength(6)])
    });
}

或组件中的第二个选项:

flagFormControl: FormGroup = new FormGroup({
  username: new FormControl('', [Validators.required, Validators.minLength(3)])
... etc
});

在您的 Form-html 代码中:

<form *ngIf="flagFormControl" [formGroup]="flagFormControl" (submit)="createSomething()">
...
<button mat-raised-button color="primary [disabled]="!flagFormControl.valid">Create Something</button>
</form>

【讨论】:

    【解决方案2】:

    对于最新的角度,您可以使用下面的简单代码在类型脚本中验证您的表单

    假设您的表单如下所示

    <form [formGroup]="userForm" novalidate (ngSubmit)="onSubmit()">
    

    你可以像这样验证它的状态

     if (!this.userForm.valid) {
        return;
      }
    

    【讨论】:

      【解决方案3】:

      除了像@tihoroot 提到的那样在类中声明一个 FormGroup 之外,您可能还想在类定义中获取一个 formControl 的实例,如下所示:

      get flagFormControl() { return this.flagForm.get('flagFormControl'); }

      否则 Angular 无法找到所需字段的实例。

      【讨论】:

        【解决方案4】:

        有必要在类中实例化一个表单,像这样

        flagForm: FormGroup;
        

        【讨论】:

          【解决方案5】:

          请更正 angular 中禁用的语法

           <button mat-button type="submit" [disabled]="!flagForm.valid" color="primary" class="btn btn-accent m-btn m-btn--air m-btn--custom">Submit</button>
          

          【讨论】:

          • 哦,是的,我也试过了......我得到'TypeError:无法读取未定义的属性'有效''
          猜你喜欢
          • 2013-02-24
          • 2014-08-11
          • 2019-04-08
          • 1970-01-01
          • 1970-01-01
          • 2021-02-05
          • 1970-01-01
          • 2011-02-20
          • 1970-01-01
          相关资源
          最近更新 更多