在Angular 6与Bootstrap 4中实现单选按钮组点击切换功能
Hey there! Since you're already using [(ngModel)] to bind your radio buttons to the usecase property, the simplest way to trigger a toggle function is to leverage Angular's (ngModelChange) event. This event fires every time the value of usecase changes—exactly when a user clicks one of your buttons.
Here's how to get this working step by step:
Step 1: Update Your Template
Add the (ngModelChange) event handler to your radio inputs, and bind Bootstrap's active class to keep the UI in sync (Bootstrap won't automatically update this class based on ngModel alone):
<div class="btn-group btn-group-toggle" data-toggle="buttons"> <label class="btn btn-secondary" [class.active]="usecase === customer"> <input type="radio" [(ngModel)]="usecase" name="options" id="option1" [value]="customer" (ngModelChange)="onUsecaseChange($event)" > Kundenzuordnung </label> <label class="btn btn-secondary" [class.active]="usecase === stock"> <input type="radio" [(ngModel)]="usecase" name="options" id="option2" [value]="stock" (ngModelChange)="onUsecaseChange($event)" > Lagerware </label> </div>
Step 2: Add the Toggle Logic to Your Component
In your component class, define the onUsecaseChange method to handle the toggle action. Make sure you've also set up the required properties:
import { Component } from '@angular/core'; @Component({ selector: 'app-your-component', // Replace with your component's actual selector templateUrl: './your-component.component.html' }) export class YourComponent { usecase: string; // Adjust the type if needed (e.g., number, custom enum) customer = 'customer'; // Replace with your actual value for Kundenzuordnung stock = 'stock'; // Replace with your actual value for Lagerware onUsecaseChange(selectedValue: any) { // Your custom toggle logic goes here console.log('Selected option:', selectedValue); if (selectedValue === this.customer) { // Logic to run when Kundenzuordnung is selected console.log('Switched to Kundenzuordnung view'); } else if (selectedValue === this.stock) { // Logic to run when Lagerware is selected console.log('Switched to Lagerware view'); } } }
Critical Check: Import FormsModule
To use [(ngModel)], you must import FormsModule in your Angular module. If you haven't already, add this to your module file:
import { FormsModule } from '@angular/forms'; @NgModule({ imports: [ // ... other imports (e.g., BrowserModule) FormsModule ], declarations: [YourComponent] }) export class YourModule { }
This approach keeps your code Angular-native—no need for jQuery or direct Bootstrap JS calls, which is the recommended practice for Angular applications.
内容的提问来源于stack exchange,提问作者Sithys

