表单无效的Angular + Material时禁用提交表单

时间:2018-02-09 13:11:28

标签: angular typescript angular-material

使用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();
        }
      }
    }

5 个答案:

答案 0 :(得分:1)

请更正角度

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

答案 1 :(得分:1)

有必要在类中实例化一个表单,比如这个

{{1}}

答案 2 :(得分:0)

除了在类中将FormGroup声明为@tihoroot之外,您可能希望在类定义中获取formControl的实例,如下所示:

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

否则Angular无法找到必填字段的实例。

答案 3 :(得分:0)

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

假设你的表单是这样的

== PASS == [passed-1 passed]
== PASS == [passed-3 passed]
== PASS == [passed-5 passed]
!! FAIL !! [failed-2 failed]
!! FAIL !! [failed-4 failed]
== PASS == [passed-1 passed]
== PASS == [passed-3 passed]
== PASS == [passed-5 passed]
!! FAIL !! [failed-2 failed]
!! FAIL !! [failed-4 failed]

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

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

答案 4 :(得分:0)

您的表单未定义,解决此问题:

在您的组件中:

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>