I have the problem that my form fields in Angular. For my object (CreatePayment) the fields are null although I check this with *ngIf
. I use the Angular version 14
payment-model-dialog.component
export class PaymentModalDialogComponent implements OnInit {
public createPaymentForm: FormGroup;
public readonly destroySubject = new Subject<void>();
constructor(
private paymentService: PaymentService,
public modalRef: MatDialogRef<PaymentModalDialogComponent>
) {
this.createPaymentForm = new FormGroup({
title: new FormControl('', [Validators.required]),
description: new FormControl(''),
});
}
ngOnInit(): void {
}
public createPayment(): void {
const payment: CreatePayment = {
title: this.createPaymentForm.get('title').value,
description: this.createPaymentForm.get('description').value,
}
this.paymentService.createPayment(payment);
}
}
payment-modal-dialog.component.html
<form [formGroup]="createPaymentForm">
<mat-form-field>
<mat-label
for="payment-titel">Titel</mat-label>
<input matInput id="payment-titel" formControlName="title"/>
<mat-error
*ngIf="createPaymentForm.controls['title'].invalid &&
createPaymentForm.controls['titel'].touched">
<label *ngIf="createPaymentForm.controls['titel'].hasError('required')">Dies ist ein Pflichtfeld.</label>
</mat-error>
</mat-form-field>
<mat-form-field>
<mat-label
for="payment-description">Beschreibung</mat-label>
<input matInput id="payment-description" formControlName="description"/>
<mat-error
*ngIf="createPaymentForm.controls['description'].invalid &&
createPaymentForm.controls['description'].touched">
<label *ngIf="createPaymentForm.controls['description'].hasError('required')">Dies ist ein Pflichtfeld.</label>
</mat-error>
</mat-form-field>
</form>
Error Message
error TS2531: Object is possibly 'null'. title: this.createPaymentForm.get('title').value,
error TS2531: Object is possibly 'null'. description: this.createPaymentForm.get('description').value,
This error message should not come up because I query the field with *ngIf
.
I hope you can help me? Many thanks :-)
CodePudding user response:
It needs checking in the code and not in the HTML. You can do the checking by if statement or simply use question marks "Non-null assertion operator" like:
title: this.createPaymentForm?.get('title')?.value,
description: this.createPaymentForm?.get('description')?.value,
Here you can find a good guide to the Non-null assertion operator: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html