Answer the question
In order to leave comments, you need to log in
Why is the mat-radio-button state reset when opening several identical forms at once?
Good afternoon. I am using Angular 9 and mat-radio-button. I'm populating the user's passport with data from the server, and made the choice of radio-button immediately based on that data using two-way binding. Radio-button is affixed immediately, everything is fine. But if I open another user's passport next to it, then on the form of the first passport, the radio-button selection is reset, i.e. no radio-button is selected. If I select on the first form, then it is reset to the second. All other data is preserved. And in the model, all the data also remains. When the radio-button is clicked, the data in the model is updated. Tell me, please, what could be the problem?
user.component.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>
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; }
);
}
}
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();
}
}
export class Gender {
public id: number;
public name: string;
constructor() {
this.id = 3;
this.name = 'Не задан';
}
}
Answer the question
In order to leave comments, you need to log in
I found the answer to the question myself. I <mat-radio-group>
had inside
<mat-card>
<form class="example-form">
...
</form>
</mat-card>
<form>
replaced with <mat-card-content>
and removed name="gender" from <mat-radio-group>
, and only after that the binding worked and the radio-button state stopped resetting. I didn't think that this could be a problem.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question