重置 Angular 9 中的单选按钮状态



我正在使用Angular 9和mat-radio-button。我用来自服务器的数据填写用户护照。我想在接收数据时立即选择正确的单选按钮,所以我设置了双向绑定。单选按钮是可选的。但是,如果我打开另一个用户护照,那么在新护照中选择了单选按钮,而在旧护照中它完全消失了 - 没有选择单个单选按钮。所有其他用户数据仍保留在表单上。此外,在模型中保存所有信息,当您选择单选按钮时,信息会发生变化。请告诉我,可能有什么问题?

用户组件.html

<mat-radio-group aria-label="Пол" [(ngModel)]="user.gender.id" name="gender">
<mat-radio-button [value]=1>Муж.</mat-radio-button>
<mat-radio-button [value]=2>Жен.</mat-radio-button>
</mat-radio-group>

user.component.ts

import { Component, OnInit } from '@angular/core';
import { UserService } from '../service/user.service';
import { User } from '../../models/user/user';
import { Data } from '../../../home/home.component';
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
public user: User;
constructor(data: Data, private userService: UserService) {
if (data != undefined) {
this.user = data as unknown as User;
this.Get(this.user.id);
}
else {
this.user = new User();
}
}
ngOnInit(): void {
}
private Get(id: number) {
this.userService.Get(id).subscribe(
data => { this.user = (data as any).user as User; }
);
}
}

用户.ts

import { Gender } from "../doctors/Gender";
export class User {
public id: number;
public name: string;
public surname: string;
public patronymic: string;
public gender: Gender;
public login: string;
public passwordHash: string;
public birthday: Date;
public employmentDateInAlpha: Date;
constructor() {
this.id = 0;
this.name = '';
this.surname = '';
this.patronymic = '';
this.gender = new Gender();
this.login = '';
this.passwordHash = '';
this.birthday = new Date();
this.employmentDateInAlpha = new Date();
}
}

性别.ts

export class Gender {
public id: number;
public name: string;
constructor() {
this.id = 3;
this.name = 'Не задан';
}
}

这是用户护照对象的外观

我自己找到了问题的答案。我的<mat-radio-group>在里面

<mat-card>
<form class = "example-form">
...
</form>
</mat-card>

我用<mat-card-content>替换了<form>并从<mat-radio-group>中删除了name = "gender",只有在那之后,绑定工作和单选按钮状态才停止重置。我不认为这可能是一个问题。

最新更新