The .ts file
export class ClassComponent implements OnInit {
est = true;
barca = false;
real = false;
constructor() {}
ngOnInit(): void {}
changeVal(inp: any) {
switch (inp) {
case 'barca':
this.est = false;
this.barca = true;
this.real = false;
break;
case 'real':
this.est = false;
this.barca = false;
this.real = true;
break;
case 'est':
this.est = true;
this.barca = false;
this.real = false;
break;
default:
break;
}
}
}
The .html file
<p [ngClass]="{'est': est, 'barca': barca, 'real': real}">class works!</p>
<input type="radio" name="class" (click)="changeVal('est')">est <br>
<input type="radio" name="class" (click)="changeVal('barca')">barca<br>
<input type="radio" name="class" (click)="changeVal('real')">real<br>
My intention is that, everytime someone click on the radio button barca, the barca value change to true and the others false, and so on for the others it works but I want to know if there is a better way to make it
CodePudding user response:
This is my solution for your issue, create a property that stores the class name, then on button click, just set the class name to the property.
ts
export class ClassComponent implements OnInit {
className = '';
constructor() {}
ngOnInit(): void {}
}
}
html
<p [ngClass]="className">class works!</p>
<input type="radio" name="class" (click)="className = 'est'">est <br>
<input type="radio" name="class" (click)="className = 'barca'">barca<br>
<input type="radio" name="class" (click)="className = 'real'">real<br>
CodePudding user response:
ts
export class ClassComponent implements OnInit {
className = '';
constructor() {}
ngOnInit(): void {}
}
}
html
<p >class works!</p>
<input type="radio" name="class" value="est" [(ngModel)]="className">est <br>
<input type="radio" name="class" value="barca" [(ngModel)]="className">barca<br>
<input type="radio" name="class" value="real" [(ngModel)]="className">real<br>
Here's what I'd do. Use the form inputs just like others to change the value of a variable, use that var to set the class of you paragraph.