0

Not long started with Angular.

So I need to add a class to a parent div when a radio button is selected in Angular. I have been led to believe that this can be possible using [ngClass] and maybe even with [ngSelected] but haven't had any luck with it in the last few days.

What I think I am looking for is a class to be added to a div when a radio button is selected, I have seen static examples of this but nothing dynamic.

<div id="one">
<id="two">
<input type="radio" /><label>Text 1</label>
</div>
</div>

when the radio button is selected, the class will be added to the div with the id="one". It seems to be quite a simple thing but I am having no love with this at all.

Thanks!

Amir Christian
  • 597
  • 6
  • 20

5 Answers5

2

First of all, make id=one to class=one(make one a class). Then use [clas.classname]="condition"

<div class="one" [class.myClass]="isChecked">
  <div id="two">
     <input id="radio" type="radio" (change)="checked($event)">
  </div>
</div>

And finally in .ts file, isChecked = checkbox.checked;

See this working demo

Harun Or Rashid
  • 5,589
  • 1
  • 19
  • 21
  • That's awesome Harunur! Out of interest, if I wanted to have multiple radio buttons, and only change the background to that radio button that has been checked, how would I go about this? – Catch-A-Big-Fish Oct 21 '19 at 10:42
  • Then you have to keep track of which radio button is checked using id attribute. See this `https://stackoverflow.com/questions/53294631/how-can-i-bind-event-of-one-or-more-arithmatic-operation-to-checkbox/53294782#53294782` – Harun Or Rashid Oct 21 '19 at 11:40
  • I am sure this works but I am being asked to complete this task in an Angular fashion. Appreciate the link though! – Catch-A-Big-Fish Oct 21 '19 at 14:19
1

You can do something like this

<div [className]="condition ? 'example-class' : 'other-class'"></div>

Please refer to this link for more details: Class Binding in Angular

MubashirEbad
  • 289
  • 1
  • 7
0

Ya you can Do like that :

addClass = false;

radioChanage(event) {
 this.addClass = true;
 }

in the template.

<div id="one" [ngClass]="{'className' : addClass}">
<id="two">
<input type="radio" (change)="radioChanage($event)" /><label>Text 1</label>
</div>
</div>
upinder kumar
  • 819
  • 6
  • 8
0

Try this

<div id="one" [class.newClass]="radioBtn">
    <div id="two" >
        <input type="radio" [ngModel]="radioBtn" /><label>Text 1</label>
    </div>
</div>
Amir Christian
  • 597
  • 6
  • 20
0

In your component

selected: string = '';

In your html

<div id="one" [ngClass]="{'myClass': selected == 'one'}">
    <div id="two">
        <input type="radio" value="one" [(ngModel)]="selected" /><label>Text 1</label>
    </div>
</div>

Regards

Charly Sosa
  • 565
  • 3
  • 5