I'm using reactive form group with Angular Material design. However, I'm getting an error:
ERROR TypeError: Cannot read property 'invalid' of undefined
Pointing to this line of code:
<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>
In Angular, a reactive form is a FormGroup that is made up of FormControls. The FormBuilder is the class that is used to create both FormGroups and FormControls.
Template Driven Forms are based only on template directives, while Reactive forms are defined programmatically at the level of the component class. Reactive Forms are a better default choice for new applications, as they are more powerful and easier to use.
A FormGroup aggregates the values of each child FormControl into one object, with each control name as the key. It calculates its status by reducing the status values of its children. For example, if one of the controls in a group is invalid, the entire group becomes invalid.
The FormArray is a way to Manage collection of Form controls in Angular. The controls can be FormGroup, FormControl, or another FormArray. Because it is implemented as Array, it makes it easier dynamically add controls.
There are two options you have.
Option 1
Wrap the element with a div or span with below check
*ngIf="fieldName && fieldName.invalid"
Option 2
Always use:
fieldName?.invalid
When you want to access invalid property of fieldName
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With