Dynamically Creating a Radio Button name in Angular 8(Typescript, HTML, SCSS)-ThrowExceptions

Exception or error:

I am having some challenges creating a radio button name Dynamically. How can I Dynamically generate a radio button name. Here is my html code

<table>
    <td>
        <input type="radio" #radio [id]="inputId" name="radio" />
        <label [for]="inputId">
        <ng-content></ng-content>
        </label>
    </td>
    <br />
    <br />
</table>

I am also passing a string to the Radio Buttton Component like this

<radio-button>
    <b>Radio Button 1</b>
</radio-button>
<radio-button>
    <b>Radio Button 2</b>
</radio-button>
<radio-button>
    <b>Radio Button 3</b>
</radio-button>
<radio-button>
    <b>Radio Button 4</b>
</radio-button>

My name attribute is hard-coded to the component like name="radio". I want to generate a dynamically assigned names for the radio button

How to solve:

You can try a for loop inside your html and put radio button code inside that and have your radio button tag something like below:

<input type="radio" name="rbtn[{{i}}]" [attr.name]="i" [value]="" />

###

Note: If you pass separate name to each radio button then you will be able to select multiple radio options. If you pass same name to multiple radio buttons then you will be able to select only one radio button.

How to Pass Dynamic Name?

If <radio-button> is a separate component. then you can pass the name as an attribute to the component like this.

<radio-button name="radio-1"></radio-button>

then in your radio-button component you can accept the coming attribute with @Input decorator.

@Input name: string;

Now you can pass this variable to your component html.

<input type="radio" #radio [id]="inputId" [name]="name" />

If you want to pass the variable to the attribute then you need to use [] for one way binding.

See an example here.
https://stackblitz.com/edit/angular-dynamic-radio-name

Leave a Reply

Your email address will not be published. Required fields are marked *