Reputation: 21
I have an ngFor loop going on some membership options. I would like to change the text inside the button from select to selected once the user chooses their options. The code i have now unfortunately changes all three buttons to selected when one has been clicked.
Typescript:
export class SelectPlanComponent implements OnInit {
plans: any;
selectedPlan?: Plan;
buttonValue = "Select";
constructor(private service: PlansService) { }
ngOnInit(): void {
this.service.getPlans()
.subscribe((response) => {
this.plans = response;
console.log(response);
});
}
onSelect(plan: Plan): void {
this.selectedPlan = plan;
this.buttonValue = "Selected"
}
}
HTML:
<div class="card" *ngFor="let plan of plans">
<h2>{{plan.title}}</h2>
<p >£{{plan.amount}}</p>
<p>{{plan.duration}}</p>
<div class="benefits-container">
<div class="benefits" *ngFor="let item of plan.description.items">
<div class="icon-container">
<mat-icon>check</mat-icon>
</div>
<p>{{item}}</p>
</div>
</div>
<a class="inverted-button" [class.selected]="plan === selectedPlan" (click)="onSelect(plan)">{{buttonValue}}</a>
</div>
Thank you in advance
Upvotes: 0
Views: 62
Reputation: 1606
You should create a property on the Plan object to keep track of whether it has been selected or not. Do this by modifying your Plan class to include a selected property, like this:
export class Plan {
// existing properties go here
selected: boolean;
}
Then, in your onSelect()
method, you can set the selected property on the plan object to true when it is selected, like this:
onSelect(plan: Plan): void {
this.selectedPlan = plan;
plan.selected = true;
this.buttonValue = "Selected";
}
In your HTML, you can use this selected property to conditionally render the "Selected" text on the button, like this:
<a class="inverted-button" [class.selected]="plan === selectedPlan" (click)="onSelect(plan)">
{{ plan.selected ? "Selected" : "Select" }}
</a>
Upvotes: 1
Reputation: 102
You currently have one variable which is bound to all buttons. What you could do is the following
Checking if the selectedPlan is the plan for the current button
<div class="card" *ngFor="let plan of plans">
<h2>{{plan.title}}</h2>
<p >£{{plan.amount}}</p>
<p>{{plan.duration}}</p>
<div class="benefits-container">
<div class="benefits" *ngFor="let item of plan.description.items">
<div class="icon-container">
<mat-icon>check</mat-icon>
</div>
<p>{{item}}</p>
</div>
</div>
<a class="inverted-button" [class.selected]="plan === selectedPlan" (click)="onSelect(plan)">{{plan === selectedPlan ? 'selected' : 'select' }}</a>
</div>
and after that you can change your TypeScript Code as follows:
onSelect(plan: Plan): void {
this.selectedPlan = plan;
}
Upvotes: 0