1

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

7
  • ng-content projects content. Are you passing a string into the component <example-component>Radio Button Label</example-component> Commented Feb 25, 2020 at 4:29
  • Hi, I am passing a string to the Radio Buttton Component like ``` html <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> ``` Commented Feb 25, 2020 at 4:43
  • As of right now, your code works stackblitz. So I'm not sure what the issue is. Commented Feb 25, 2020 at 4:49
  • Hi, what happens is that my name attribute is hard-coded name="radio". I want a generic name( dynamically assigned names) for the radio button Commented Feb 25, 2020 at 5:02
  • You could bind it to a local variable [name]="localVariable" Commented Feb 25, 2020 at 5:03

2 Answers 2

1

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]="" />
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.