Remove or add class in Angular - css

I have a list and the plugin (dragula) I used, adds certain CSS class on certain action. I am using Angular 5. I want to find out the presence of certain class (myClass) and remove that and replace with (yourClass). In jQuery we can do that like this
$( "p" ).removeClass( "myClass" ).addClass( "yourClass" );
How can I achieve this in Angular5. Here the main issue is that myClass is added automatically to the selected li by the plugin. So using a function I cant set the class.
When I tried with renderer2, it is removing the CSS class and adding another class. But it is adding only to the first li. My code is:
let myTag ;
myTag = this.el.nativeElement.querySelector("li");
this.renderer.addClass(myTag, 'gu-mirrorss')
this.renderer.removeClass(myTag, 'dragbox');
<div class="right-height" id ='dest' [dragula]='"second-bag"' [dragulaModel]="questions">
{{ questions.length == 0 ? ' Drag and drop questions here ' : ' '}}
<li #vc data-toggle="tooltip" data-placement="bottom" title= {{question.questionSentence}} class="well dragbox" *ngFor="let question of questions; let i = index" [attr.data-id]="question.questionId" [attr.data-index]="i" (click)="addThisQuestionToArray(question,i, $event)" [class.active]="isQuestionSelected(question)" #myId > {{question.questionId}} {{question.questionSentence}}</li>
</div>

Import ElementRef from angular core and define in constructor then try below code:
Below line of code will give you first occurrence of <p> tag from Component. querySelector gives you first item and querySelectorAll gives you all items from DOM.
import { Component, ElementRef } from "#angular/core";
constructor(private el: ElementRef) {
}
let myTag = this.el.nativeElement.querySelector("p"); // you can select html element by getelementsByClassName also, please use as per your requirement.
Add Class:
if(!myTag.classList.contains('myClass'))
{
myTag.classList.add('myClass');
}
Remove Class:
myTag.classList.remove('myClass');

You can use id in your html
<button #namebutton class="btn btn-primary">login</button>
add viewchild in your.ts
#ViewChild('namebutton', { read: ElementRef, static:false }) namebutton: ElementRef;
create a function that will trigger the event
actionButton() {
this.namebutton.nativeElement.classList.add('class-to-add')
setTimeout(() => {
this.namebutton.nativeElement.classList.remove('class-to-remove')
}, 1000);
}
and call the function.
If your native element is undefined check this answer
Angular: nativeElement is undefined on ViewChild

Here are multiple ways to pass classes
<some-element [ngClass]="'first second'">...</some-element>
<some-element [ngClass]="['first', 'second']">...</some-element>
<some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element>
<some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element>
<some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>
From Official Docs

If you want to change all li.myClass, you can do like this:
Note the #questions in the container div.
Component.ts
#ViewChild('questions') questions: any;
questions.nativeElement.querySelectorAll('.myClass').forEach(
question => {
question.classList.remove('myClass');
question.classList.add('newClass');
}
)
Component.html
<div #questions class="right-height" id ='dest' [dragula]='"second-bag"' [dragulaModel]="questions">
{{ questions.length == 0 ? ' Drag and drop questions here ' : ' '}}
<li
#vc
data-toggle="tooltip"
data-placement="bottom"
title= {{question.questionSentence}}
class="well dragbox"
*ngFor="let question of questions; let i = index"
[attr.data-id]="question.questionId"
[attr.data-index]="i"
(click)="addThisQuestionToArray(question,i, $event)"
[class.active]="isQuestionSelected(question)"
#myId>
{{question.questionId}} {{question.questionSentence}}
</li>
</div>

The Best and easiest way is : -
If student is null then dissabled else not. Use this in button attribute. If you are using bootstrap theme
[ngClass]="{disabled: (students === null) ? true : false}"

If 'yourFlag' is true, 'classB' is enabled.
This worked in angular10.
class="classA {{yourFlag ? 'classB' : ''}}"

Related

How to make autosuggest field look like bootstrap input?

How can I make the <vue-autosuggest> input look like the input from BootstrapVue (<b-input>)?
To apply the form-control class to vue-autosuggest's inner <input>, as required for the Bootstrap <input> styles, you could use the inputProps prop (automatically applied to the <input>):
<template>
<vue-autosuggest :input-props="inputProps">
...
</vue-autosuggest>
</template>
<script>
export default {
data() {
return {
inputProps: {
class: 'form-control',
}
}
}
}
</script>
Interestingly, that class used to be added by default in vue-autosuggest 1.x, but was removed in 2.x.
demo
You need to modify the the <input> tag of the vue-autosuggest component to include the class form-control from Vue-Bootstrap.
You will not be able to add this class directly to the component as the component wraps the input within a div block. Bootstrap CSS requires the the element to be of type input to properly match the CSS selectors.
If we look here https://github.com/darrenjennings/vue-autosuggest/blob/master/src/Autosuggest.vue at the component itself we see
<input
:type="internal_inputProps.type"
:value="internalValue"
:autocomplete="internal_inputProps.autocomplete"
:class="[isOpen ? `${componentAttrPrefix}__input--open` : '', internal_inputProps['class']]"
v-bind="internal_inputProps"
aria-autocomplete="list"
:aria-activedescendant="isOpen && currentIndex !== null ? `${componentAttrPrefix}__results-item--${currentIndex}` : ''"
:aria-controls="`${componentAttrIdAutosuggest}-${componentAttrPrefix}__results`"
#input="inputHandler"
#keydown="handleKeyStroke"
v-on="listeners"
>
This must be modified in your local version to include the bootstrap class.

How to use [ngClass] in a *ngFor Angular component without a local index keeper?

I'm using the following markup to mark the clicked component as active.
<div *ngFor="let menu of menus;"
(click)="onClick($event,menu.link)"
[ngClass]="{'active':menu.active}">
{{menu.title}}
</div>
The method handling the click is as follows.
onClick(target, link) {
target.active = !target.active;
this.router.navigate([{ outlets: { primary: [""], menus: [link] } }]);
}
It seems that the value of target.active goes from undefined to true to false to true etc. but the style doesn't get set. (I'm printing out the whole component to the console and can't see the addition of the class' name.)
Question: What am I missing in this approach?
NB, I know how to resolve it by approaching it from a different angle. I set up a local variable keeping the index and setting it like shown here. The aim of my question is to learn to achieve the requested behavior in a more like-a-bossy way.
target here:
onClick(target, link) {
target.active = !target.active; <------------
this.router.navigate([{ outlets: { primary: [""], menus: [link] } }]);
}
doesn't refer to menu, it refers to the event. But based on your ngClass directive:
[ngClass]="{'active':menu.active}">
You need to set active to menu variable and so it can be done like this:
<div *ngFor="let menu of menus;"
(click)="onClick(menu,menu.link)"
[ngClass]="{'active':menu.active}">
{{menu.title}}
</div>
Instead of passing in the $event, send it the actual menu object. Like this:
<div *ngFor="let menu of menus;"
(click)="onClick(menu)"
[ngClass]="{'active':menu.active}">
{{menu.title}}
</div>
And in the component:
onClick(menu) {
menu.active = !menu.active;
this.router.navigate([{ outlets: { primary: [""], menus: [menu.link] } }]);
}

How to add a class to an element when another element gets a class in angular?

I have a scrollspy directive that adds an ".active" class to a nav item. When the first nav item has the ".active" class I want my header bar to contain a certain class too. Attached is a simplified example, but how can I add ".active" to item 1 by only looking at the classes in item 2. jsfiddle
<div ng-app>
<div ng-controller='ctrl'>
<div id="item1" ng-class="if item2 has class=active then add active class here">Item 1</div>
<div id="item2" ng-class="myVar">Item 2</div>
</div>
//I can't use a scope object I can only look at item 2's classes
<button type="button" ng-click="myVar='active'">Add Class</button>
<button type="button" ng-click="myVar=''">Remove Class</button>
Click here for live demo.
You'll need a directive to interact with the element. I would have the directive watch the element's classes and have it call a function from your controller when the classes change. Then, your controller function can apply the logic specific to your need, which is to set a flag letting another element know how to respond.
angular.module('myApp', [])
.controller('MyCtrl', function($scope) {
$scope.foo = function(classes) {
if (~classes.indexOf('active')) {
$scope.otherItemIsActive = true;
}
};
})
.directive('onClassChange', function() {
return {
scope: {
onClassChange: '='
},
link: function($scope, $element) {
$scope.$watch(function() {
return $element[0].className;
}, function(className) {
$scope.onClassChange(className.split(' '));
});
}
};
})
;

Updating element CSS on PageA from button on PageB

I am using tabs for an app. I want a user button which when clicked on tab-detail.html to update the CSS of an element on its parent tab page tab.html
.controller('TabCtrl', function($scope,Tabs) {
$scope.tabs = Tabs.all() ;
// this populates the "tab.html" template
// an element on this page is: <span id="tab_selected_1">
// when user selects a listed item on tab.html
// it calls tab-detail.html
})
.controller('TabDetailCtrl', function($scope,$stateparams,Tabs) {
$scope.tabs = Tabs.get($stateparams.tabID) ;
// on tab-detail.html is a button <button ng-click="tabSelect()">
$scope.tabSelect = function(thisID) {
// update css on TabCtrl elementID
document.getElementById('tab_selected_1').style.color = "green" ;
}
})
The only way to get to tab-detail.html is via tab.html, thus tab.html must be loaded. But no matter what method I try I can't seem to find a way to access the element that is on another controller's page.
I have tried:
var e = angluar.element('tab_selected_1');
or
var e = angluar.element(document.querySelector('tab_selected_1') ;
e.style.color = "green" ;
The approach you are doing will never do a JOB for you as the DOM you want isn't available. You could achieve this by creating a sharable service that will maintain all of this variable in it and it will be used on UI. For ensuring binding of them your service variable should be in object structure like styleData OR you could also achieve this by creating angular constant.
app.constant('constants', {
data: {
}
});
Then you could inject this constant inside you controller & modify it.
.controller('TabCtrl', function($scope, Tabs, constants) {
$scope.constants = constants; //make it available constants on html
$scope.tabs = Tabs.all() ;
// this populates the "tab.html" template
// an element on this page is: <span id="tab_selected_1">
// when user selects a listed item on tab.html
// it calls tab-detail.html
})
.controller('TabDetailCtrl', function($scope,$stateparams,Tabs, constants) {
$scope.tabs = Tabs.get($stateparams.tabID) ;
$scope.constants= constants; //make it available constants on html
// on tab-detail.html is a button <button ng-click="tabSelect()">
$scope.tabSelect = function(thisID) {
// update css on TabCtrl elementID
$scope.constants.data.color = "green" ;
}
})
Markup
<div id="tab_selected_1" ng-style="{color: constants.data.color || 'black'}">
one way to do this is ....
1) Create a service
2) set a value to a variable in service on button click(tab-detail.html)
3) use that service variable value in tab.html
(Correction update at bottom)
#pankajparkar solution does work, however it does not work with IONIC as the IONIC Framework somehow overrides the DOM settings. Via the DOM Element inspector an see: style='color:green' being added inline to the ITEM/SPAN and can see the element defined as: element.style{ color: green}...but the color of the rendered HTML does not change....it stays black.
Further research shows this is somehow an IONIC problem as other users have the same problem. Other SOFs and blogs indicate that there appears to be a work around but I have yet to see it work.
The above is reformatted for others future use (even though it doesn't work with IONIC), thus I am still looking for a solution to work with IONIC:
.constant('constants', {
tabColors: {
curID:0,
},
})
.controller('TabCtrl', function($scope,Tabs,constants) {
$scope.constants = constants;
}
.controller('TabDetailCtrl', function($scope,$stateparams,Tabs,constants) {
$scope.constants = constants;
$scope.setItem= function(thisID) {
$scope.constants.tabColors.oldID = $scope.constants.tabColors.curID ;
delete $scope.constants.tabColors['tabID_'+$scope.constants.tabColors.curID] ;
$scope.constants.tabColors.curID = thisID ;
$scope.constants.tabColors['tabID_'+thisID] = 'green' ;
}
// HTML in Tab.html
<span id='tab_tabID_{{tab.tabID}}' ng-style="{color: constants.tabColors['tabID_'+tab.tabID] || 'black'}">
Some Text Here
</span>
//HTML in TabDetail.html
<button id="tab_button" class="button button-small button-outline button-positive" ng-click="setItem({{tab.tabID}});">
Select This Item
</button>
Correction: This method does work and does work with IONIC. The problem with IONIC is every element embedded within an ionic tag <ion-item>... <ion-nav>
...etc inherits its own properties from predefined classes...so you must either update the class (not optimal) or have ID tags on every element and/or apply CSS changes (using above method) to every child element. This is not optimal however it will work.
In my case my HTML actually looked like:
<span id='tab_tabID_{{tab.tabID}}' ng-style="{color: constants.tabColors['tabID_'+tab.tabID] || 'black'}">
<h2>Header Text Here</h>
<p>More text here</p>
</span>
The above CSS method works with this:
<span id='tab_tabID_{{tab.tabID}}'>
<h2 ng-style="{color: constants.tabColors['tabID_'+tab.tabID] || 'black'}">
Header Text Here
</h>
<p ng-style="{color: constants.tabColors['tabID_'+tab.tabID] || 'black'}">
More text here
</p>
</span>

What is the best way to conditionally apply a class?

Lets say you have an array that is rendered in a ul with an li for each element and a property on the controller called selectedIndex. What would be the best way to add a class to the li with the index selectedIndex in AngularJS?
I am currently duplicating (by hand) the li code and adding the class to one of the li tags and using ng-show and ng-hide to show only one li per index.
If you don't want to put CSS class names into Controller like I do, here is an old trick that I use since pre-v1 days. We can write an expression that evaluates directly to a class name selected, no custom directives are necessary:
ng:class="{true:'selected', false:''}[$index==selectedIndex]"
Please note the old syntax with colon.
There is also a new better way of applying classes conditionally, like:
ng-class="{selected: $index==selectedIndex}"
Angular now supports expressions that return an object. Each property (name) of this object is now considered as a class name and is applied depending on its value.
However these ways are not functionally equal. Here is an example:
ng-class="{admin:'enabled', moderator:'disabled', '':'hidden'}[user.role]"
We could therefore reuse existing CSS classes by basically mapping a model property to a class name and at the same time keep CSS classes out of Controller code.
ng-class supports an expression that must evaluate to either
A string of space-delimited class names, or
An array of class names, or
A map/object of class names to boolean values.
So, using form 3) we can simply write
ng-class="{'selected': $index==selectedIndex}"
See also How do I conditionally apply CSS styles in AngularJS? for a broader answer.
Update: Angular 1.1.5 has added support for a ternary operator, so if that construct is more familiar to you:
ng-class="($index==selectedIndex) ? 'selected' : ''"
My favorite method is using the ternary expression.
ng-class="condition ? 'trueClass' : 'falseClass'"
Note: Incase you're using a older version of Angular you should use this instead,
ng-class="condition && 'trueClass' || 'falseClass'"
I'll add to this, because some of these answers seem out of date. Here's how I do it:
<class="ng-class:isSelected">
Where 'isSelected' is a javascript variable defined within the scoped angular controller.
To more specifically address your question, here's how you might generate a list with that:
HTML
<div ng-controller="ListCtrl">
<li class="ng-class:item.isSelected" ng-repeat="item in list">
{{item.name}}
</li>
</div>
JS
function ListCtrl($scope) {
$scope.list = [
{"name": "Item 1", "isSelected": "active"},
{"name": "Item 2", "isSelected": ""}
]
}
See: http://jsfiddle.net/tTfWM/
See: http://docs.angularjs.org/api/ng.directive:ngClass
Here is a much simpler solution:
function MyControl($scope){
$scope.values = ["a","b","c","d","e","f"];
$scope.selectedIndex = -1;
$scope.toggleSelect = function(ind){
if( ind === $scope.selectedIndex ){
$scope.selectedIndex = -1;
} else{
$scope.selectedIndex = ind;
}
}
$scope.getClass = function(ind){
if( ind === $scope.selectedIndex ){
return "selected";
} else{
return "";
}
}
$scope.getButtonLabel = function(ind){
if( ind === $scope.selectedIndex ){
return "Deselect";
} else{
return "Select";
}
}
}
.selected {
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
<div ng-app ng-controller="MyControl">
<ul>
<li ng-class="getClass($index)" ng-repeat="value in values" >{{value}} <button ng-click="toggleSelect($index)">{{getButtonLabel($index)}}</button></li>
</ul>
<p>Selected: {{selectedIndex}}</p>
</div>
I faced a similar problem recently and decided to just create a conditional filter:
angular.module('myFilters', []).
/**
* "if" filter
* Simple filter useful for conditionally applying CSS classes and decouple
* view from controller
*/
filter('if', function() {
return function(input, value) {
if (typeof(input) === 'string') {
input = [input, ''];
}
return value? input[0] : input[1];
};
});
It takes a single argument, which is either a 2-element array or a string, which gets turned into an array that is appended an empty string as the second element:
<li ng-repeat="item in products | filter:search | orderBy:orderProp |
page:pageNum:pageLength" ng-class="'opened'|if:isOpen(item)">
...
</li>
If you want to go beyond binary evaluation and keep your CSS out of your controller you can implement a simple filter that evaluates the input against a map object:
angular.module('myApp.filters, [])
.filter('switch', function () {
return function (input, map) {
return map[input] || '';
};
});
This allows you to write your markup like this:
<div ng-class="muppets.star|switch:{'Kermit':'green', 'Miss Piggy': 'pink', 'Animal': 'loud'}">
...
</div>
The was I recently did that was doing this:
<input type="password" placeholder="Enter your password"
ng-class="{true: 'form-control isActive', false: 'isNotActive'}[isShowing]">
The isShowing value is a value that is located on my controller that gets toggled with the click of a button and the parts between the single parenthesis are classes I created in my css file.
EDIT: I would also like to add that codeschool.com has a free course that is sponsored by google on AngularJS that goes over all of this stuff and then some. There is no need to pay for anything, just signup for an account and get going!
Best of luck to you all!
Ternary operator has just been added to angular parser in 1.1.5.
So the simplest way to do this is now :
ng:class="($index==selectedIndex)? 'selected' : ''"
We can make a function to manage return class with condition
<script>
angular.module('myapp', [])
.controller('ExampleController', ['$scope', function ($scope) {
$scope.MyColors = ['It is Red', 'It is Yellow', 'It is Blue', 'It is Green', 'It is Gray'];
$scope.getClass = function (strValue) {
switch(strValue) {
case "It is Red":return "Red";break;
case "It is Yellow":return "Yellow";break;
case "It is Blue":return "Blue";break;
case "It is Green":return "Green";break;
case "It is Gray":return "Gray";break;
}
}
}]);
</script>
And then
<body ng-app="myapp" ng-controller="ExampleController">
<h2>AngularJS ng-class if example</h2>
<ul >
<li ng-repeat="icolor in MyColors" >
<p ng-class="[getClass(icolor), 'b']">{{icolor}}</p>
</li>
</ul>
<hr/>
<p>Other way using : ng-class="{'class1' : expression1, 'class2' : expression2,'class3':expression2,...}"</p>
<ul>
<li ng-repeat="icolor in MyColors">
<p ng-class="{'Red':icolor=='It is Red','Yellow':icolor=='It is Yellow','Blue':icolor=='It is Blue','Green':icolor=='It is Green','Gray':icolor=='It is Gray'}" class="b">{{icolor}}</p>
</li>
</ul>
You can refer to full code page at ng-class if example
I am new to Angular but have found this to solve my issue:
<i class="icon-download" ng-click="showDetails = ! showDetails" ng-class="{'icon-upload': showDetails}"></i>
This will conditionally apply a class based on a var.
It starts off with a icon-download as a default, the using ng-class, I check the status of showDetails if true/false and apply class icon-upload. Its working great.
Hope it helps.
This works like a charm ;)
<ul class="nav nav-pills" ng-init="selectedType = 'return'">
<li role="presentation" ng-class="{'active':selectedType === 'return'}"
ng-click="selectedType = 'return'"><a href="#return">return
</a></li>
<li role="presentation" ng-class="{'active':selectedType === 'oneway'}"
ng-click="selectedType = 'oneway'"><a href="#oneway">oneway
</a></li>
</ul>
This will probably get downvoted to oblivion, but here is how I used 1.1.5's ternary operators to switch classes depending on whether a row in a table is the first, middle or last -- except if there is only one row in the table:
<span class="attribute-row" ng-class="(restaurant.Attributes.length === 1) || ($first ? 'attribute-first-row': false || $middle ? 'attribute-middle-row': false || $last ? 'attribute-last-row': false)">
</span>
This is in my work multiple conditionally judge:
<li ng-repeat='eOption in exam.examOptions' ng-class="exam.examTitle.ANSWER_COM==exam.examTitle.RIGHT_ANSWER?(eOption.eoSequence==exam.examTitle.ANSWER_COM?'right':''):eOption.eoSequence==exam.examTitle.ANSWER_COM?'wrong':eOption.eoSequence==exam.examTitle.RIGHT_ANSWER?'right':''">
<strong>{{eOption.eoSequence}}</strong> |
<span ng-bind-html="eOption.eoName | to_trusted">2020 元</span>
</li>
Here is another option that works well when ng-class can't be used (for example when styling SVG):
ng-attr-class="{{someBoolean && 'class-when-true' || 'class-when-false' }}"
(I think you need to be on latest unstable Angular to use ng-attr-, I'm currently on 1.1.4)
well i would suggest you to check condition in your controller with a function returning true or false .
<div class="week-wrap" ng-class="{today: getTodayForHighLight(todayDate, day.date)}">{{day.date}}</div>
and in your controller check the condition
$scope.getTodayForHighLight = function(today, date){
return (today == date);
}
partial
<div class="col-md-4 text-right">
<a ng-class="campaign_range === 'thismonth' ? 'btn btn-blue' : 'btn btn-link'" href="#" ng-click='change_range("thismonth")'>This Month</a>
<a ng-class="campaign_range === 'all' ? 'btn btn-blue' : 'btn btn-link'" href="#" ng-click='change_range("all")'>All Time</a>
</div>
controller
$scope.campaign_range = "all";
$scope.change_range = function(range) {
if (range === "all")
{
$scope.campaign_range = "all"
}
else
{
$scope.campaign_range = "thismonth"
}
};
If you are using angular pre v1.1.5 (i.e. no ternary operator) and you still want an equivalent way to set a value in both conditions you can do something like this:
ng-class="{'class1':item.isReadOnly == false, 'class2':item.isReadOnly == true}"
If you having a common class that is applied to many elements you can create a custom directive that will add that class like ng-show/ng-hide.
This directive will add the class 'active' to the button if it's clicked
module.directive('ngActive', ['$animate', function($animate) {
return function(scope, element, attr) {
scope.$watch(attr.ngActive, function ngActiveWatchAction(value){
$animate[value ? 'addClass' : 'removeClass'](element, 'active');
});
};
}]);
More info
Just adding something that worked for me today, after much searching...
<div class="form-group" ng-class="{true: 'has-error'}[ctrl.submitted && myForm.myField.$error.required]">
Hope this assists in your successful development.
=)
Undocumented Expression Syntax : Great Website Link... =)
Check this.
The infamous AngularJS if|else statement!!!
When I started using Angularjs, I was a bit surprised that I couldn’t find an if/else statement.
So I was working on a project and I noticed that when using the if/else statement, the condition shows while loading.
You can use ng-cloak to fix this.
<div class="ng-cloak">
<p ng-show="statement">Show this line</span>
<p ng-hide="statement">Show this line instead</span>
</div>
.ng-cloak { display: none }
Thanks amadou
You can use this npm package. It handles everything and has options for static and conditional classes based on a variable or a function.
// Support for string arguments
getClassNames('class1', 'class2');
// support for Object
getClassNames({class1: true, class2 : false});
// support for all type of data
getClassNames('class1', 'class2', ['class3', 'class4'], {
class5 : function() { return false; },
class6 : function() { return true; }
});
<div className={getClassNames({class1: true, class2 : false})} />
I understand this question id for angular, but if anyone is using React or a React-Based Framework (Amplify, NextJS, Serverless, etc.) The solution is significantly easier. The most performant way is with a ternary operator like so:
<div className={condition ? "classnameiftrue" : "classnameiffalse"}>
You can use this strategy to animate the tree if using useState() as each time the state changes it will reload that conditional with the new value.

Resources