I'm currently using bootstrap v4.5 in my Angular project and whenever I click on my dropdown button, its value remains the same irrespective of the dropdown menu item I'm clicking. I want the text of my dropdown button to change to whatever dropdown menu item I'm clicking on. Can someone pleas help me with this.
My HTML code:
<div >
<button type="button" id="dropdownMenuButton2" data-bs-toggle="dropdown" aria-expanded="false">
2021
</button>
<div aria-labelledby="dropdownMenuButton2">
<a >2011</a>
<a >2012</a>
<a >2013</a>
<a >2014</a>
</div>
</div>
CodePudding user response:
The functionality that you're looking for can be found in the HTML tag
<select>
<option value="2011">2011</option>
<option value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
</select>
CodePudding user response:
Bootstrap is a style library only (with some JavaScript but only for interactions) This template shows how to create a dropdown, but for the logic part, you will have to integrate it with your frontend framework.
In native JavaScript, it would be up to you to update the text directly when you detect a click. With Angular, I guess it's possible to make it reactive. You should be able to create a dynamic state, which is reflected in the button text, and which you update when the list is clicked.
I'm not an Angular specialist, so I'll let the experts answer you on this point
CodePudding user response:
There may be times you want to emulate a <select>
element with a dropdown
. Here's how you can achieve that with angularJS.
angular.module('myApp', [])
.controller('myController', ['$scope', function($scope) {
$scope.years = [];
let y = 2010,
thisyear = new Date().getFullYear();
while ( y <= thisyear) $scope.years.push(y);
$scope.chosenYear = thisyear;
$scope.chooseYear = function(y) {
$scope.chosenYear = y;
}
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.1/angular.min.js"></script>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C OGpamoFVy38MVBnE IbbVYUew OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho j7jyWK8fNQe A12Hb8AhRq26LrZ/JpcUGGOn Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<div ng-app="myApp" ng-controller="myController">
<div >
<button type="button" id="dropdownMenuButton2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
{{chosenYear}}
</button>
<div aria-labelledby="dropdownMenuButton2">
<a ng-repeat='year in years' href="#" ng-click='chooseYear(year)'>{{year}}</a>
</div>
</div>
</div>