I have a work and stuck it 2 days. Hope everyone know angularjs help me :).
I need to force a change html when have a change on model. Example:
This is html code:
<!--CAKE LIST-->
<div id="cakelist" ng-controller="CakeListCtrl">
<ul class="thumbnails cake-rack" cakes="cakes" ng-model="cakesModel">
<li class="pull-left cake-unit" ng-repeat="cake in cakes" cake="cake">
<div class="thumbnail">
<a href="{{cake.link}}">
<img ng-src="{{cake.avatar}}" alt="{{cake.title}}" class="img img-rounded img-polaroid" />
</a>
<h5 class="pull-left">
{{cake.title}}
</h5>
Shared
<div class="clearfix"></div>
<ul class="attrs unstyled">
<li>
<div class="pull-left">Mã sản phẩm</div>
<span class="pull-right">{{cake.type}}</span>
</li>
</ul>
</div>
</li>
</ul>
<input type="button" class="btn btn-primary" value="add more cake" class="cake-more" ng-click="addCake()" />
<input type="button" class="btn btn-danger" value="clear cake" class="cake-clear" ng-click="clear()" />
<img alt="Loading" src="/imagesroot/ajax-loader-1.gif" loading-stage="loadingStage" class="cake-loading"/>
</div>
now a have a menu outside of controller:
<div id="cake-catalog" class="cake-catalog">
<ul class="nav">
<li class="active">
<a cake-menu-unit href="sacmscategory50c2302b7ff0a">Nhân vật hoạt hình</a>
</li>
<li>
<a cake-menu-unit href="sacmscategory50c2308717a84">Động vật</a>
</li>
<li>
<a cake-menu-unit href="sacmscategory50c2309da00f6">Tạo hình 3D</a>
</li>
<li>
<a cake-menu-unit href="sacmscategory50c230ba08d9d">Các mẫu hình khác</a>
</li>
</ul>
</div>
I have angular module for add and clear:
var CakeList = angular.module('CakeList', ['ngResource']);
CakeList.service('CakeService', function($rootScope) {
var cakedata = [{avatar:"test", title: "test2"}];
$rootScope.loadCake = false;
var bf = function() { $rootScope.loadCake=true; };
var at = function() { $rootScope.loadCake=false; };
return {
cakes: function() {
bf();
at();
return cakedata;
},
addCake: function() {
bf();
cakedata.push(cake);
at();
},
clear: function() {
cakedata = []; console.log('clear');
}
};
});
CakeList.directive('cakeCatalog', function($rootScope, CakeService) {
var clickfn = function(e) {
e.preventDefault();
CakeService.clear();
};
var nonclickfn = function(e) {
e.preventDefault();
console.log('nonclickfn');
};
return {
restrict: "C",
link: function(scope, element, attrs) {
$rootScope.$watch('loadCake', function(newValue, oldValue) {
if (newValue===true) {
element.find('a').off('click').on('click', nonclickfn);
}
else {
element.find('a').off('click').on('click', clickfn);
}
});
}
};
But when runtime, i put click on a element of menu then the list cake not clear, even i check console.log in console box and see the cakedata really clear!. Can you help me this case ? :)
First of all, the design seems a bit weird by using everywhere $rootScope (among other things). But that's not the cause of the problem. The problem is the $watch which is not correct.
First of all, use loadCake as an object instead of a primitive type:
var loadCake = { loaded: false};
Use the objectEquality parameter in your $watch statement:
$rootScope.$watch('loadCake', function(newValue, oldValue) {
if (!newValue) return;
if (newValue.loaded === true) {
element.find('a').off('click').on('click', nonclickfn);
}
else {
element.find('a').off('click').on('click', clickfn);
}
}, true);
Related
I have a controller which is populating content to content areas using ng-repeat. The issue is that some of this content needs to come front template files and so needs to be compiled 'on the fly'. Right now I have this function dynamically adding content:
$scope.layouts = [
{ id: 'Dashboard', icon: 'dashboard', view: '/qph/views/Dashboard.php' },
{ id: 'Customers', icon: 'people', view: '/qph/views/users.php' },
{ id: 'Quotes', icon: 'format_list_bulleted', view: '/qph/views/Quotes.php' }
];
$scope.workspace = {};
var getTemplate = function(id){
var view = 'test.php';
$timeout(function() { //added timeout
if($templateCache.get(view) === undefined) {
$templateRequest(view).then(function (data) {
$scope.workspaces.forEach(function (v) {
if (v.id == id) v.content = $compile(data)($scope);
});
});
} else {
$scope.workspaces.forEach(function (v) {
if (v.id == id) v.content = $compile($templateCache.get(view))($scope);
});
}
}, 2000);
};
$scope.workspaces =
[
{ id: 1, name: "Dashboard", icon: 'dashboard', active:true }
];
getTemplate(1);
I have checked that the data variable has the html content as expected, but the compile is outputting the following:
{"0":{"jQuery331075208394539601512":{"$scope":"$SCOPE","$ngControllerController":{}}},"length":1}
Does anyone know why its not compiling the html content as expected?
Here is the template content for reference:
<div class="col-sm-6 col-sm-offset-3" ng-controller="UserController">
<div class="col-sm-6 col-sm-offset-3">
<div class="well">
<h3>Users</h3>
<button class="btn btn-primary" style="margin-bottom: 10px" ng-click="user.getUsers()">Get Users!</button>
<ul class="list-group" ng-if="user.users">
<li class="list-group-item" ng-repeat="user in user.users">
<h4>{{user.name}}</h4>
<h5>{{user.email}}</h5>
</li>
</ul>
<div class="alert alert-danger" ng-if="user.error">
<strong>There was an error: </strong> {{user.error.error}}
<br>Please go back and login again
</div>
</div>
</div>
</div>
Here is the tabs view that is to display the compiled content:
<ul class="nav nav-tabs workspace-tabs">
<li class="nav-item" ng-repeat="space in workspaces">
<a class="nav-link" data-toggle="tab" href="#workspace{{space.id}}" ng-class="(space.active == true ) ? 'active show': ''">
<span class="hidden-sm-up"><i class="material-icons md-24">{{space.icon}}</i></span>
<span class="hidden-xs-down">{{space.name}}</span>
<button ng-click="workspace.remove($index)">x</button>
</a>
</li>
</ul>
<div class="tab-content workspace-content">
<div ng-repeat="space in workspaces" id="workspace{{space.id}}" class="tab-pane fade in" ng-class="(space.active == true ) ? 'active show': ''">
{{space.content}}
</div>
</div>
The $compile service creates a jqLite object that needs to be added to the DOM with a jqLite or jQuery append() method. Using interpolation {{ }} will only render the stringified value of the jqLite object.
<div class="tab-content workspace-content">
<div ng-repeat="space in workspaces" id="workspace{{space.id}}" class="tab-pane fade in" ng-class="(space.active == true ) ? 'active show': ''">
̶{̶{̶s̶p̶a̶c̶e̶.̶c̶o̶n̶t̶e̶n̶t̶}̶}̶
<compile html="space.html"></compile>
</div>
</div>
Instead, use a custom directive to compile and append the HTML data to the DOM:
app.directive("compile", function($compile) {
return {
link: postLink,
};
function postLink(scope, elem, attrs) {
var rawHTML = scope.$eval(attrs.html)
var linkFn = $compile(rawHTML);
var $html = linkFn(scope);
elem.append($html);
}
})
For more information, see AngularJS Developer Guide - HTML Compiler.
Use a directive.
app.directive('myCustomer', function() {
return {
templateUrl: 'test.php',
controller: 'UserController'
};
})
Template cache will be managed automatically.
I have a mean stack application where there is a left panel for navigation. One of the tabs have a form, and after I submit the form, I call a function, which after successful completion has a $state.go('secured.dashboard'); which redirects it to another tab(dashboard). This works fine, but on the left panel the previous tab(application form tab) is still highlighted as active. Although, On clicking the tab, the active menu is highlighted correctly.
So, the problem is when I click submit, it redirects to a different tab(dashboard) but on the left-navigation panel, some other tab(application Form) is highlightened, although I change the variable $scope.selectedMenu = "dashboard";. I have added the relevant code snippets from files:
header-template.html
<nav class="navbar-default navbar-side" role="navigation" style="width:200px">
<div class="sidebar-collapse">
<ul class="nav" id="main-menu">
<li>
<a id="page1" ng-class='{"active-menu": selectedMenu == "dashboard"}' ui-sref="secured.dashboard" ng-click='selectedMenu = "dashboard"'><i class="fa fa-dashboard "></i>Dashboard</a>
</li>
<li>
<a id="page2" ng-class='{"active-menu": selectedMenu == "applicationForm"}' ui-sref="secured.applicationForm" ng-click='selectedMenu = "applicationForm"'><i class="fa fa-handshake-o "></i>Application Forms</a>
</li>
<li>
<a id="page3" ng-class='{"active-menu": selectedMenu == "adminprofile"}' ui-sref="secured.adminprofile" ng-click='selectedMenu = "adminprofile"' ng-show="adminUserTrue"><i class="fa fa-user-secret"></i>Administrator</a>
</li>
<li>
<a id="page4" ng-class='{"active-menu": selectedMenu == "managerProfile"}' ui-sref="secured.managerProfile" ng-click='selectedMenu = "managerProfile"' ng-show="isManager"><i class="fa fa-user-secret"></i>Manager</a>
</li>
<li>
<a ng-class='{"active-menu": selectedMenu == "logout"}' href="" ng-click="logout()" ng-click='selectedMenu = "logout"'><i class="fa fa-sign-out fa-fw"></i> Logout</a>
</li>
</ul>
</div>
</nav>
dashboard.js
(function() {
var app = angular.module('dashboard', []);
app.config(['$stateProvider', function($stateProvider) {
$stateProvider.state('secured.dashboard', {
url: '/dashboard',
controller: 'DashboardController',
templateUrl: '/views/dashboard.html'
});
}]);
app.controller('DashboardController', ['$scope', 'AuthService', 'user', '$state', '$http', function($scope, AuthService, user, $state, $http) {
console.log("yes, the controller is here");
$scope.user = user;
AuthService.setUser(user);
$scope.applicationShow = {};
$scope.logout = function() {
AuthService.logout().then(function() {
$scope.user = null;
$state.go('unsecured');
})
}
applicationForm.js
(function() {
var app = angular.module('applicationForm', []);
app.config(['$stateProvider', function($stateProvider) {
$stateProvider.state('secured.applicationForm', {
url: '/applicationForm',
controller: 'applicationFormController',
templateUrl: '/views/applicationForm.html',
params: {
obj: null
}
});
}]);
app.controller('applicationFormController', ['$http', '$scope', '$state', '$uibModal', function($http, $scope, $state, $uibModal) {
console.log($state.params.obj);
if ($state.params.obj == null) {
$scope.application = {
technical: false,
business: false
};
} else {
$scope.application = $state.params.obj;
}
console.log("I am finally the application");
console.log($scope.application);
$scope.submitApplication = function() {
$scope.submitted = true;
console.log("Submit called");
console.log($scope.application.title);
console.log($scope.user.email);
console.log("Yes, i am here!");
console.log($scope.application.userEmail);
$scope.application.state = "SUBMITTED";
$scope.application.heirarchy = $scope.managerjson[$scope.application.managerName].senior;
console.log($scope.application.heirarchy);
var check = 0;
$http.get('/application/applicationlistNum/').then(function(response) {
$scope.application.number = response.data.value.sequence_value;
console.log($scope.application.number);
for (var i = 0, len = $scope.applicationList.length; i < len; i++) {
if ($scope.applicationList[i]._id == $scope.application._id) {
check = 1;
console.log("matched");
break;
}
}
if (check == 1) {
$http.put('/application/applicationlist/' + $scope.application._id, $scope.application).then(function(response) {
refresh();
});
} else {
$http.post('/application/applicationList', $scope.application).then(function(response) {
console.log("Successfully submitted");
refresh();
});
}
swal({
title: "Great!",
text: "We have received your request",
type: "success",
timer: 3000,
confirmButtonText: "Wohoo!"
});
var contactInfo = {
managerEmail: $scope.application.managerName,
selfEmail: $scope.application.userEmail,
name: $scope.managerjson[$scope.application.managerName].name
};
clear();
sendMail(contactInfo);
console.log("changing states");
$scope.selectedMenu = "dashboard";
$state.go('secured.dashboard');
});
};
applicationForm.html
<div class="col-lg-12">
<form class="well form-horizontal" id="contact_form" ng-submit="submitApplication()" name="form">
<fieldset>
<!-- some more fields -->
<div class="form-group">
<label class="col-md-4 control-label"></label>
<div class="col-md-2">
<button type="submit" class="btn btn-primary"> Submit <span class="glyphicon glyphicon-send"></span></button>
<!-- <button class="btn btn-primary" ng-click="submitApplication()"> Submit <span class="glyphicon glyphicon-send"></span></button> -->
</div>
<div>
<button class="btn btn-warning" ng-click="saveApplication()"> Save <span class="glyphicon glyphicon-floppy-disk"></span></button>
</div>
</div>
</fieldset>
</form>
In applicationForm.js change $scope.selectedMenue = 'dashboard' to
$scope.selectedMenu = {name : "dashboard"};
And in your header template
<ul class="nav" id="main-menu">
<li>
<a id="page1" ng-class='{"active-menu": selectedMenu.name == "dashboard"}' ui-sref="secured.dashboard" ng-click='selectedMenu.name= "dashboard"'><i class="fa fa-dashboard "></i>Dashboard</a>
</li>
<li>
<a id="page2" ng-class='{"active-menu": selectedMenu.name== "applicationForm"}' ui-sref="secured.applicationForm" ng-click='selectedMenu.name= "applicationForm"'><i class="fa fa-handshake-o "></i>Application Forms</a>
</li>
<li>
<a id="page3" ng-class='{"active-menu": selectedMenu.name== "adminprofile"}' ui-sref="secured.adminprofile" ng-click='selectedMenu.name= "adminprofile"' ng-show="adminUserTrue"><i class="fa fa-user-secret"></i>Administrator</a>
</li>
<li>
<a id="page4" ng-class='{"active-menu": selectedMenu.name== "managerProfile"}' ui-sref="secured.managerProfile" ng-click='selectedMenu.name= "managerProfile"' ng-show="isManager"><i class="fa fa-user-secret"></i>Manager</a>
</li>
<li>
<a ng-class='{"active-menu": selectedMenu.name== "logout"}' href="" ng-click="logout()" ng-click='selectedMenu.name= "logout"'><i class="fa fa-sign-out fa-fw"></i> Logout</a>
</li>
</ul>
I have two controllers headerController, aboutController.
headerController -> To maintain the navigation and redirection
aboutController -> works when about-us page loads.
My issue is I have to update the headerController variable value when aboutController loads. i.e When about us page loads, the navigation about-us should active, similar to all the pages.
This is my code:
app.service('shareService', function () {
var data;
return {
getProperty: function () {
return data;
},
setProperty: function (value) {
data = value;
}
};
});
app.controller('headerController', function ($scope, shareService) {
$scope.navigation = [
{url: '#!/home', name: 'Home'},
{url: '#!/about-us', name: 'About Us'},
{url: '#!/services', name: 'Services'}
];
var data = shareService.getProperty();
console.log(data);
$scope.selectedIndex = 0;
$scope.itemClicked = function ($index) {
console.log($index);
$scope.selectedIndex = $index;
};
});
app.controller('aboutController', function ($scope, shareService) {
console.log('test');
$scope.selectedIndex = 1;
shareService.setProperty({navigation: $scope.selectedIndex});
});
header.html:
<header ng-controller="headerController">
<div class="header">
<div class="first-half col-md-6">
<div class="row">
<div class="logo">
<img src="assets/img/logo.png" alt=""/>
</div>
</div>
</div>
<div class="second-half col-md-6">
<div class="row">
<div class="social-share">
<ul id="social-share-header">
<li><i class="fa fa-facebook" aria-hidden="true"></i></li>
<li><i class="fa fa-twitter" aria-hidden="true"></i></li>
<li><i class="fa fa-google-plus" aria-hidden="true"></i></li>
</ul>
</div>
</div>
</div>
<nav>
<ul ng-repeat="nav in navigation">
<li class="main-nav" ng-class="{ 'active': $index == selectedIndex }"
ng-click="itemClicked($index)">
{{nav.name}}
</li>
</ul>
</nav>
</div>
</header>
index.html
This is how my template works.
<body ng-app="myApp">
<section class="first-section">
<div ng-include="'views/header.html'"></div>
</section>
<section class="second-section">
<div ng-view></div>
</section>
<section class="last-section">
<div ng-include="'views/footer.html'"></div>
</section>
</body>
Update 1: Added index.html file.
Update 2: Issue explanation: If I run directly to the about us page, then still the home navigation is on active. But it should be About us
What is you are looking for is event based communication between your controllers. This can be easily done using. $rootScope.$on, $rootScope.$emit and $rootScope.$broadcast. Since explaining all three of them in this answer will be overkill. Kindly go through this article
I have a directive called filterButton, which will let user to select the filter option and add the check mark on the right. Now I have a reset button in filter.html. Once the user click the reset button, all the filter field will set back to default. I had tried couple methods, it didn't work. Any suggestion? Thank you in advance.
app.js
app.directive('filterButton', function () {
return {
restrict: 'EA',
templateUrl: 'template/filter-button.html',
replace: true,
scope: {
list: '=', //two-way binding
selected: '=', //two-way binding
field: '#', //one-way binding
},
link: function ($scope) {
$scope.selected = [];
$scope.setSelectedOption = function() {
var id = this.option.id;
if(_.contains($scope.selected, id)) {
$scope.selected = _.without($scope.selected, id)
} else {
$scope.selected.push(id);
}
return false;
};
$scope.isChecked = function(id) {
if(_.contains($scope.selected, id)) {
return "fa fa-check pull-right-selected";
}
return "";
};
}
}
});
filter-button.html
<div class="row filter-item">
<div class="btn-group" dropdown is-open="{open: open}">
<button type="button" class="btn btn-primary dropdown-toggle" dropdown-toggle ng-disabled="disabled">Fiter By {{field}} <span class="caret"></span></button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu">
<li data-ng-repeat="option in list" class="dropdown-btn"> <a data-ng-click="setSelectedOption()">{{option.name}}<span data-ng-class="isChecked(option.id)"></span></a></li>
</ul>
</div>
filter.html
<filter-button list="statusList" selected="selectedStatus" field="Status" popover="Error Customer? or No Error Customer?" popover-trigger="mouseenter"></filter-button>
<filter-button list="systemList" selected="selectedSystemType" field="System Type" popover="N+1 or Stand alone?" popover-trigger="mouseenter"></filter-button>
<filter-button list="customerFilterList" selected="selectedCustomer" field="Customer" popover="Male or Female?" popover-trigger="mouseenter"></filter-button>
<div class="row filter-item">
<div class="filter-label">
<button class="btn btn-primary">Reset</button>
</div>
</div>
You can reinitialize the selected arrays on the reset click button:
<button class="btn btn-primary" ng-click="reset()">Reset</button>
In you controller:
$scope.reset = function() {
$scope.selectedStatus = [];
$scope.selectedSystemType = [];
$scope.selectedCustomer = [];
}
I am trying to work how to add a class with ngClick. I have uploaded up my code onto plunker Click here. Looking at the angular documentation i can't figure out the exact way it should be done. Below is a snippet of my code. Can someone guide me in the right direction
<div ng-show="isVisible" ng-class="{'selected': $index==selectedIndex}" class="block"></div>
Controller
var app = angular.module("MyApp", []);
app.controller("subNavController", function ($scope){
$scope.toggle = function (){
$scope.isVisible = ! $scope.isVisible;
};
$scope.isVisible = false;
});
I want to add or remove "active" class in my code dynamically on ng-click, here what I have done.
<ul ng-init="selectedTab = 'users'">
<li ng-class="{'active':selectedTab === 'users'}" ng-click="selectedTab = 'users'"><a href="#users" >Users</a></li>
<li ng-class="{'active':selectedTab === 'items'}" ng-click="selectedTab = 'items'"><a href="#items" >Items</a></li>
</ul>
You just need to bind a variable into the directive "ng-class" and change it from the controller. Here is an example of how to do this:
var app = angular.module("ap",[]);
app.controller("con",function($scope){
$scope.class = "red";
$scope.changeClass = function(){
if ($scope.class === "red")
$scope.class = "blue";
else
$scope.class = "red";
};
});
.red{
color:red;
}
.blue{
color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="ap" ng-controller="con">
<div ng-class="class">{{class}}</div>
<button ng-click="changeClass()">Change Class</button>
</body>
Here is the example working on jsFiddle
There is a simple and clean way of doing this with only directives.
<div ng-class="{'class-name': clicked}" ng-click="clicked = !clicked"></div>
you can also do that in a directive, if you want to remove the previous class and add a new class
.directive('toggleClass', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('click', function() {
if(element.attr("class") == "glyphicon glyphicon-pencil") {
element.removeClass("glyphicon glyphicon-pencil");
element.addClass(attrs.toggleClass);
} else {
element.removeClass("glyphicon glyphicon-ok");
element.addClass("glyphicon glyphicon-pencil");
}
});
}
};
});
and in your template:
<i class="glyphicon glyphicon-pencil" toggle-class="glyphicon glyphicon-ok"></i>
You have it exactly right, all you have to do is set selectedIndex in your ng-click.
ng-click="selectedIndex = 1"
Here is how I implemented a set of buttons that change the ng-view, and highlights the button of the currently selected view.
<div id="sidebar" ng-init="partial = 'main'">
<div class="routeBtn" ng-class="{selected:partial=='main'}" ng-click="router('main')"><span>Main</span></div>
<div class="routeBtn" ng-class="{selected:partial=='view1'}" ng-click="router('view1')"><span>Resume</span></div>
<div class="routeBtn" ng-class="{selected:partial=='view2'}" ng-click="router('view2')"><span>Code</span></div>
<div class="routeBtn" ng-class="{selected:partial=='view3'}" ng-click="router('view3')"><span>Game</span></div>
</div>
and this in my controller.
$scope.router = function(endpoint) {
$location.path("/" + ($scope.partial = endpoint));
};
var app = angular.module("MyApp", []);
app.controller("subNavController", function ($scope){
$scope.toggle = function (){
$scope.isVisible = ! $scope.isVisible;
};
$scope.isVisible = false;
});
<div ng-show="isVisible" ng-class="{'active':isVisible}" class="block"></div>
I used Zack Argyle's suggestion above to get this, which I find very elegant:
CSS:
.active {
background-position: 0 -46px !important;
}
HTML:
<button ng-click="satisfaction = 'VeryHappy'" ng-class="{active:satisfaction == 'VeryHappy'}">
<img src="images/VeryHappy.png" style="height:24px;" />
</button>
<button ng-click="satisfaction = 'Happy'" ng-class="{active:satisfaction == 'Happy'}">
<img src="images/Happy.png" style="height:24px;" />
</button>
<button ng-click="satisfaction = 'Indifferent'" ng-class="{active:satisfaction == 'Indifferent'}">
<img src="images/Indifferent.png" style="height:24px;" />
</button>
<button ng-click="satisfaction = 'Unhappy'" ng-class="{active:satisfaction == 'Unhappy'}">
<img src="images/Unhappy.png" style="height:24px;" />
</button>
<button ng-click="satisfaction = 'VeryUnhappy'" ng-class="{active:satisfaction == 'VeryUnhappy'}">
<img src="images/VeryUnhappy.png" style="height:24px;" />
</button>
If you prefer separation of concerns such that logic for adding and removing classes happens on the controller, you can do this
controller
(function() {
angular.module('MyApp', []).controller('MyController', MyController);
function MyController() {
var vm = this;
vm.tab = 0;
vm.setTab = function(val) {
vm.tab = val;
};
vm.toggleClass = function(val) {
return val === vm.tab;
};
}
})();
HTML
<div ng-app="MyApp">
<ul class="" ng-controller="MyController as myCtrl">
<li ng-click="myCtrl.setTab(0)" ng-class="{'highlighted':myCtrl.toggleClass(0)}">One</li>
<li ng-click="myCtrl.setTab(1)" ng-class="{'highlighted':myCtrl.toggleClass(1)}">Two</li>
<li ng-click="myCtrl.setTab(2)" ng-class="{'highlighted':myCtrl.toggleClass(2)}">Three</li>
<li ng-click="myCtrl.setTab(3)" ng-class="{'highlighted':myCtrl.toggleClass(3)}">Four</li>
</ul>
CSS
.highlighted {
background-color: green;
color: white;
}
I can't believe how complex everyone is making this. This is actually very simple. Just paste this into your html (no directive./controller changes required - "bg-info" is a bootstrap class):
<div class="form-group col-md-12">
<div ng-class="{'bg-info': (!transport_type)}" ng-click="transport_type=false">CARS</div>
<div ng-class="{'bg-info': transport_type=='TRAINS'}" ng-click="transport_type='TRAINS'">TRAINS</div>
<div ng-class="{'bg-info': transport_type=='PLANES'}" ng-click="transport_type='PLANES'">PLANES</div>
</div>
for Reactive forms -
HTML file
<div class="col-sm-2">
<button type="button" [class]= "btn_class" id="b1" (click)="changeMe()">{{ btn_label }}</button>
</div>
TS file
changeMe() {
switch (this.btn_label) {
case 'Yes ': this.btn_label = 'Custom' ;
this.btn_class = 'btn btn-danger btn-lg btn-block';
break;
case 'Custom': this.btn_label = ' No ' ;
this.btn_class = 'btn btn-success btn-lg btn-block';
break;
case ' No ': this.btn_label = 'Yes ';
this.btn_class = 'btn btn-primary btn-lg btn-block';
break;
}