我正在使用具有Angular Material设计的反应形式组。但是,我收到一个错误:
错误TypeError:无法读取未定义的属性“invalid”
指向这行代码:
<input formControlName="fieldName" ngDefaultControl matInput placeholder="Field Name">
<mat-error *ngIf="fieldName.invalid">
Field name is required
</mat-error>
TS:
export class AddFieldComponent implements OnInit {
form: FormGroup;
constructor(public fb: FormBuilder) {
this.form = this.fb.group({
fieldName: ['', Validators.required],
fieldType: ['', Validators.required]
});
}
}
HTML
<div [formGroup]="form" class="add-field">
<div mat-dialog-content>
<h2>Add Fields</h2>
<mat-form-field>
<input formControlName="fieldName" ngDefaultControl matInput placeholder="Field Name">
<mat-error *ngIf="fieldName.invalid">
Field name is required
</mat-error>
</mat-form-field>
<mat-form-field>
<mat-select formControlName="fieldType">
<mat-option value="text-field">Text Field</mat-option>
<mat-option value="radio-btn">Radio Button</mat-option>
</mat-select>
</mat-form-field>
</div>
<div mat-dialog-actions>
<span class="right-align-next-element"></span>
<button class="secondary-btn" mat-button (click)="closeModal()">Cancel</button>
<button [disabled]="fieldName.invalid" class="primary-btn" mat-button (click)="addFields()" cdkFocusInitial>Add field</button>
</div>
</div>
你有两种选择。
选项1
用下面的检查用div或span包裹元素
*ngIf="fieldName && fieldName.invalid"
选项2
始终使用:
fieldName?.invalid
当您要访问fieldName的无效属性时