对于我的对象,字段是空的,虽然我用*ngIf检查这一点



我有一个问题,我的表单字段在Angular。对于我的对象(CreatePayment),字段是空的,尽管我用*ngIf检查了这一点。我用的是Angular版本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 TS2531: Object is possibly 'null'. title: this.createPaymentForm.get('title').value,
error TS2531: Object is possibly 'null'. description: this.createPaymentForm.get('description').value,

这个错误信息不应该出现,因为我用*ngIf查询字段。

我希望你能帮助我。非常感谢:-)

需要在代码中检查,而不是在HTML中检查。您可以通过if语句进行检查,也可以使用问号"非空断言操作符"进行检查。如:

title: this.createPaymentForm?.get('title')?.value,
description: this.createPaymentForm?.get('description')?.value,

在这里你可以找到一个很好的非空断言操作符指南:https://www.typescriptlang.org/docs/handbook/release notes/typescript - 2 - 0. - html

相关内容

最新更新