I use two times an Angular component that (both) contains a form.
But when a mat-radio-button
is selected, the other ones are deselected (even on the second component).
The problem happend only with the mat-radio-group
input.
There is my component:
myform-form.component.html
<form #form="ngForm">
<div style="display: flex; flex-direction: column;">
<mat-radio-group name="test" [(ngModel)]="variable">
<mat-radio-button [value]="false">False</mat-radio-button>
<mat-radio-button [value]="true">True</mat-radio-button>
</mat-radio-group>
<span>Selected: {{variable}}</span>
</div>
</form>
myform-form.component.ts
import {Component} from "@angular/core";
@Component({
selector: 'myform-form',
templateUrl: './myform-form.component.html'
})
export class FormComponent {
variable: boolean = true;
}
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<myform-form></myform-form>
<myform-form></myform-form>
`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'radiatest';
}
I expect both of my components to be independent and I don't want the first mat-radio-group
to be unchecked when the second one is checked.
There is the actual result where I am unable to check the upper and the below mat-radio-group
:
CodePudding user response:
the problem is the "name" parameter. Mat-radio-group create a serie of radio buttons with the same name that this parameter.
The solution is a bit work-around. In your component.ts you declare a variable outside the component
let myformNextUniqueId = 0;
And add a new variable to your component "id"
id:number;
constructor(){
this.id=myformNextUniqueId ;
}
Then use this variable to give the name
<mat-radio-group [name]="'test' id" [(ngModel)]="variable">
...
</mat-radio-group>
see stackblitz
Update Another option is make your component it's neccesary an attribute name
Your constructor like
constructor(@Optional() @Attribute('name') public name:string){
if (!name)
throw new Error("The name attribute it's neccessary")
}
And you write
<mat-radio-group [name]="name || 'fool'" [(ngModel)]="variable">
...
</mat-radio-group>
Obviously your app should be like
<myform-form name="one"></myform-form>
<myform-form name="two"></myform-form>