Я использую группу реактивной формы с дизайном Angular Material. Однако я получаю сообщение об ошибке:
ОШИБКА TypeError: Невозможно прочитать свойство 'invalid' из undefined
Указывая на эту строку кода:
<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>