cretae radio button in angular using native html, and select the first one by default
- User
cretae radio button in angular using native html, and select the first one by default
- Assistant
To create a radio button in Angular using native HTML, you can use the
inputelement with atypeofradio. To select the first one by default, you can use thecheckedattribute.Here’s an example:
<label> <input type="radio" name="example" value="option1" checked> Option 1 </label> <label> <input type="radio" name="example" value="option2"> Option 2 </label>In this example, the first radio button is selected by default because it has the
checkedattribute. Thenameattribute is used to group the radio buttons together so that only one option can be selected at a time. Thevalueattribute can be used to identify which option was selected when the form is submitted. - User
i have one div appear when select on any one of them
- Assistant
To make a div appear when a radio button is selected, you can use Angular's data binding and styles.
First, create the radio buttons using the native HTML as described in the previous answer. Give each radio button an
ng-modelattribute that binds to a variable in your component's TypeScript file.<label> <input type="radio" name="example" value="option1" [(ngModel)]="selectedOption"> Option 1 </label> <label> <input type="radio" name="example" value="option2" [(ngModel)]="selectedOption"> Option 2 </label>In this example, we bind the value of the selected radio button to a variable named
selectedOption.Next, add the div that you want to show or hide based on the selected option. Use Angular's
ngIfdirective to display the div only when the selected option matches the corresponding value.<div *ngIf="selectedOption === 'option1'"> Content for Option 1 </div> <div *ngIf="selectedOption === 'option2'"> Content for Option 2 </div>In this example, we use the
*ngIfdirective to show the div only whenselectedOptionmatches the corresponding value.Overall, your template file will look like this:
<label> <input type="radio" name="example" value="option1" [(ngModel)]="selectedOption"> Option 1 </label> <label> <input type="radio" name="example" value="option2" [(ngModel)]="selectedOption"> Option 2 </label> <div *ngIf="selectedOption === 'option1'"> Content for Option 1 </div> <div *ngIf="selectedOption === 'option2'"> Content for Option 2 </div>This way, the div corresponding to the selected radio button will appear, and the other div will be hidden.