将对象序列化为FormControl-Angular/Typescript



我有一个"地址";我这样给他们看。

<mat-form-field *ngIf="useSubstituteAddress" class="contact-form">
<mat-label>Ersatz Adresse</mat-label>
<mat-select [formControl]="contactDataForm.get('address')?.get('substituteAddress')! | asFormControl">
<mat-option *ngFor="let address of assosiatedAddresses" [value]="address">
{{address.postalcode}} {{address.city}}, {{address.street}} {{address.housenumber}}
</mat-option>
</mat-select>
</mat-form-field>

我从后台得到一个替代地址,我的目标是在我的选择中显示这个地址。

所以我这样做:

if (this.contactData.substituteAddress) {
this.useSubstituteAddress = true;
this.addressService.getAddressById(Number(this.contactData.substituteAddress?.id)).subscribe((address) => {
this.contactDataForm.get('address')?.get('substituteAddress')?.setValue(address);
});
}

如果我通过我的表单console.log,它会显示信息。

我的表格是这样的:

contactDataForm = new FormGroup({
address: new FormGroup({
street: new FormControl('', Validators.required),
housenumber: new FormControl('', Validators.required),
postalcode: new FormControl('', Validators.required),
city: new FormControl('', Validators.required),
addressAddition: new FormControl(''),
country: new FormControl('', Validators.required),
contactAddress: new FormControl(true),
substituteAddress: new FormControl()
}),
contact: new FormGroup({
id: new FormControl(''),
email: new FormControl('', Validators.required),
phoneNumber: new FormControl(''),
mobileNumber: new FormControl(''),
notificationsEnabled: new FormControl(true),
contactAddress: new FormControl()
})
});

当我访问我的网站时,它应该是这样的。选择查看

但它只是显示一个空白的Select。

有人参与这个问题吗?

这是因为默认情况下MatSelect使用严格的相等运算符将值与可能值的列表进行比较。如果该值不在列表中,则不会显示该值。由于两者都是对象,它会检查引用是否相等,因此它需要是同一个对象。

您可以在MatSelect上使用compareWith函数(此处为文档(。然后,它将使用提供的函数来检查两个对象之间的相等性。

我们不知道你的地址是什么,但它似乎包含一个id,所以你可以做一些事情:

compareFn(a: Address, b: Address): boolean {
return a.id === b.id;
}

在您的模板中,将compareWith绑定到函数:

<mat-form-field *ngIf="useSubstituteAddress" class="contact-form">
<mat-label>Ersatz Adresse</mat-label>
<mat-select [compareWith]="compareFn" [formControl]="contactDataForm.get('address')?.get('substituteAddress')! | asFormControl">
<mat-option *ngFor="let address of assosiatedAddresses" [value]="address">
{{address.postalcode}} {{address.city}}, {{address.street}} {{address.housenumber}}
</mat-option>
</mat-select>
</mat-form-field>

最新更新