【发布时间】: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