Angular 2 - What's the equivalent of routerLinkActive="active" inside a TypeScript (.ts) file? - css

I was using routerLinkActive="active" inside the html file with routerLink=[myId] to highlight the active anchor in a ul.
Example:
<a [routerLink]="[myId]" class="list-group-item clearfix" routerLinkActive="active">
<div class="pull-left">
<h4 class="list-group-item-heading">{{someName}}</h4>
</div>
</a>
But when I remove the [routerlink]="[myId]" and replace it with a click listener (that does some calculation and then redirects the route using this.router.navigate(['/someURL', myId]) ) the routerLinkActive="active" no longer works/highlights.
Example:
<a (click)="onClick(myId)" class="list-group-item clearfix" routerLinkActive="active">
<div class="pull-left">
<h4 class="list-group-item-heading">{{someName}}</h4>
</div>
</a>
When inspecting the anchor elements using the routerLink=[myId], the style is set to:
.list-group-item.active, .list-group-item.active:focus, .list-group-item.active:hover {
z-index: 2;
color: #fff;
background-color: #337ab7;
border-color: #337ab7;
}
Is it possible to set the active anchor style in the .ts file in the onClick() function? Or is there a simpler way around this?

Highlighting a specific link in the navigation is a reflection of the current state of the app: link A is highlighted because the user is looking at page A.
You're asking how to highlight the link as the result of a click. This approach is less than ideal: you could end up highlighting the link before the new route/page is actually activated. Most importantly, if the user reloads the page or navigates to it directly because they bookmarked it, the link will NEVER be highlighted (because no one clicked it).
You need to find a way to highlight the link based on app state, NOT as the result of an action (the typical flow is: action => changes state => updates UI).
Maybe something like this:
#Component({
template: `
<a [class.active]="currentPath == 'home'">HomeComponent</a>
`
})
export class HomeComponent {
currentPath = '';
constructor(route: ActivatedRoute) {
// Retrieve current path.
this.currentPath = snapshot.url.join('');
}
}
The idea is to retrieve the current path and expose it to the template.
Like Günter suggested, you can probably find more robust code for testing the current path in routerLinkActive's source code.

Related

How to override a css syle of `ng-template` built field without /deep/?

I have an issue with some components which using ng-template. If the component I'm using generates some elements which I don't want or contain a buggy thing, I seek for workarounds. Ideally I shouldn't do, but once there are some issues with these depending lib and I'm compelled to do so. Previously faced similar issue with popver, and now with ngx-datatable. I appreciate if you can tell me the better practice I need to follow.
i.e. here for ngx-datatabler-row-detail template I get an output with a div which has .datatable-row-detail class. If I don't override it with /deep/ (which is deprecated I heard), even !important doesn't work to override the width. How can I override these class styles for generated fields within angular component, since there is no way to give them an id ?
/deep/
.datatable-body-row{
border-bottom:1px solid #000;
}
/deep/
.datatable-row-detail{
width:600px !important;
}
<!-- Row Detail Template -->
<ngx-datatable-row-detail [rowHeight]="120" #myDetailRow (toggle)="onDetailToggle($event)">
<ng-template
...>
<div style="padding-left:35px" >
<div><strong>==== Details ===</strong></div>
<li *ngFor="let detail of row.details">
{{detail }}
</li>
</div>
</ng-template>
</ngx-datatable-row-detail>
<ngx-datatable-column>
<ng-template
...>
<a
(click)="toggleExpandRow(row)"> <i class="fa fa-cube btn-link" hover-class="active"></i>
</a>
</ng-template>
</ngx-datatable-column>
Please see this stackblits. Just remove the /deep/ from css and when you click on open you no longer see the background.
https://stackblitz.com/edit/ngx-datatable-row-detail-omuywi?file=app/app.component.css
I don't think it is possible to override the thirdparty component styles from an Angular component in a clean way. (There are options like using the deprecated deep or turning off ViewEncapsulation.)
However, overriding them is possible from the global styles.scss in the app root. If we put the following styles into it, it works:
.datatable-body-row {
border-bottom: 1px solid #000;
}
.datatable-row-detail {
background: rgb(134, 79, 79) !important;
}
Stackblitz:
https://stackblitz.com/edit/ngx-datatable-row-detail-mj3otr?file=styles.css

Adding and Removing Styles to li group using Angular 2

<ul>
<li (click)="AddColor($event)">ONE</li>
<li (click)="AddColor($event)">TWO</li>
<li (click)="AddColor($event)">THREE</li>
</ul>
AddColor(e){
e.srcElement.style.color="blue"
}
I have the above list when i click any one of the li item out of 3, the clicked label color should be changed. when i click another all item colors should be revert back to original and change color of current clicked item.
#Mehdi said, you should not access DOM directly untill there is a need.
Always keep in mind, drive your view with data rather than accessing
DOM directly
I have forked and working snippet https://plnkr.co/edit/fgINMc?p=preview
When using Angular, you don't want to directly manipulate the DOM element. Rather let angular deal with it.
In your example, you can generate your list from an array you declare in the code like so
export class YourClass{
links:any;
activeLink = -1;
//...
constructor(){
this.links = ['ONE','TWO','THREE']
}
//...
}
and then in your template you could have :
<ul>
<li *ngFor="let link of links; let i = index"
(click)="activeLink = i"
[ngClass]="activeLink == i? 'blue' : '' " >
</li>
</ul>
and declare a css class blue :
.blue{
color:blue;
}

Icon link without text eslint error

I have a React project that shows a bunch of social media links that are just icons to their respective sites. I use icomoon fonts and whatnot to provide the icon-* classes to show the social media icons.
The error I get, understandably, is:
Anchors must have content and the content must be accessible by a screen reader
What should I do in this scenario where I don't want anything but the icon and no text? I'm not sure how to properly do this so everyone's happy.
Edit
I didn't think code was necessary since it doesn't pertain to anything really.
Here's the mapping that spits out the links. As you can see, no text. Just font-icons for whatever social media site is being linked to:
{this.props.siteInfo.social.map(function(item, i){
return <a key={i} className={`nav_item icon-${item.social_media_type}-square`} href={item.url} target="_blank" rel="noopener noreferrer"></a>
})}
Which results in:
<a key="0" class="nav_item icon-facebook-square" href="facebook.com/someprofile" target="_blank" rel="noopener noreferrer"></a>
I got the same problem and I solved it by just adding one white space
<a><i class="fa fa-phone" aria-hidden="true"></i> </a>
I found my answer here:
https://silktide.com/i-thought-title-text-improved-accessibility-i-was-wrong/
It seems you should add a some text that you can hide via CSS, although not with display:none; or anything of that sort. Screen readers will ignore that.
I'm not sure if this is the most current way to do things, but it does work and achieves accessibility and eslint is happy.
I encountered the same problem, solved it like this with React (same suggestion as #danielInixon
const IconLink = props => {
const { name } = props;
return <a aria-label={name} href="https://github.com/johnb8005/svg">
<i className={`fa fa-${name}`} aria-hidden="true"/>
</a>;
};
I solved it with the CSS workaround:
Add some Text.
Add some CSS:
text-indent: 100%;
white-space: nowrap;
overflow: hidden;
That means you wrote you text in side the 'i' tag
as in
your text
instead
<a><i class="fa fa-phone" aria-hidden="true"></i> your text</a>
I had the same issues for my header design system and found a solution here:
https://github.com/gatsbyjs/gatsby/issues/20208
To clarify, here's the difference:
Before:
const ExternalButton = styled( ({ ...props}) => <a {...props} />)``
After:
const ExternalButton = styled( ({ children, ...props}) => <a {...props}{children} </ a>)
Please note that a space had to be included in the </ a> for it to render on the post. Please remove it for the functional answer

AngularJs translation directive stop working when I change div class using jquery

Well, being straight forward the problem is my $scope.$apply() is also not digesting the changes to rerun the translate directive.
I show you the HTML with applied translation directive and jQUERY code to change the class on resize of the windows (client).
HTML for menu:
<div id="navigation" ng-cloak>
<div class="container-fluid">
BRAND NAME
<ul class='main-nav'>
<li ng-class="{'active':activeLink == 'home'}">
<a href="#/">
<span>Home</span>
</a>
</li>
<li ng-class="{'active':activeLink == 'planning'}" data-trigger="hover">
<a href="#" data-toggle="dropdown" class='dropdown-toggle'>
<span>Planning</span>
<span class="caret"></span>
</a>
<ul class="dropdown-menu">
<a href="#" data-toggle="dropdown" class='dropdown-toggle'>Goals</a>
<ul class="dropdown-menu">
<li>
{{'TOP_MENU.GOAL_LIST' | translate}}
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
HERE is the JQuery Code to make it responsive for screen size changes.
function checkLeftNav() {
var $w = $(window),
$content = $("#content"),
$left = $("#left");
if ($w.width() <= 840) {
if (!$left.hasClass("mobile-show")) {
$left.hide();
$("#main").css("margin-left", 0);
}
if ($(".toggle-mobile").length == 0) {
$("#navigation .user").after('<i class="fa fa-bars"></i>');
}
if ($(".mobile-nav").length == 0) {
createSubNav();
}
} else {
if (!$left.is(":visible") && !$left.hasClass("forced-hide") && !$("#content").hasClass("nav-hidden")) {
$left.show();
$("#main").css("margin-left", $left.width());
}
$(".toggle-mobile").remove();
$(".mobile-nav").removeClass("open");
if ($content.hasClass("forced-fixed")) {
$content.removeClass("nav-fixed");
$("#navigation").removeClass("navbar-fixed-top");
}
if ($w.width() < 1200) {
if ($("#navigation .container").length > 0) {
versionFluid();
$('body').addClass("forced-fluid");
}
} else {
if ($('body').hasClass("forced-fluid")) {
versionFixed();
}
}
}
}
Now What my solution was to get he nav element scope on which the jquery is applying class and call the $apply() on its scope. which is not working.
Solution Code:
$(window).resize(function(e) {
checkLeftNav();
// get the scope of element and apply $apply()
var sc = angular.element('.mobile-nav').scope();
sc.$apply();
});
But still when ever the screen size is changed to mobile view less than 840 I can see direct code values instead of translated text in menu like this. and When I change back to screen width more than 840 it shows correct translated text. I am experimenting this on chrome on my pc by resizing. I checked on mobile its not translating there too.
AngularJS provides two-way data binding, not two way everything binding. It's not intended to be used this way. $apply() only looks at the data model - it is the function you call when you want to say "Hey, Angular, I've updated the data model, come have a look!" That is literally its only purpose. There is no method in Angular designed to look at the DOM itself for changes - that's very inefficient and against Angular's philosophies anyway, which is why it ships without jQuery.
You might want to evaluate other frameworks that better support this kind of thing. However, if you really wish to do this you can easily convert it into a proper AngularJS module. The best way is to simply paste all of this code into a controller, and then change the window resize binding to use Angular's $window service, like:
var windowElement = angular.element($window);
windowElement.bind('resize', function() {
// Do my calculations here.
});
With your calculations would you compute the same variables but you would store them in scope variables and then adjust your template to use them. For example, what you're doing with $(".toggle-mobile").remove(); could be replaced by:
if (windowElement.width > 840) {
// Other code here
$scope.isMobile = false;
} else {
$scope.isMobile = false;
}
and in your template:
<i class="fa fa-bars"></i>
Give it a whirl, play with it for a week or two, and you'll never go back to jQuery. It takes a lot of getting used to, but once you do you realize how broken the whole "I'm looking at my template and have no idea what mystery event handlers are bound to all this stuff" concept was to begin with.

Is it possible to set a style of link that shows only when the linked webpage is being viewed?

I got a problem like this (this is html/css menu):
Eshop | Another eshop | Another eshop
Client wants it work like this:
User comes to website, clicks on Eshop. Eshop changes to red color with red box outline. User decides to visit Another eshop, so Eshop will go back to normaln color without red box outline, and another eshop will do the red outline trick again..
I know there is A:visited but I don't want all visited menu links to be red with red box outline.
Thx for any help :)
The same that Joe Skora has written but more specific:
.red {
outline-color:red;
outline-width:10px;
}
Now you could use Javascript (in this example using jQuery) in the click-event-handler:
$('.red').removeClass('red'); // removes class red from all items with class red
$(this).addClass('red'); // adds class red to the clicked item
Another way of doing it is the use of the pseudo selector :target.
For informations about it: www.thinkvitamin.com
You can do this with plain CSS and HTML. A method we commonly use is to have a matching ID and class selector for each navigation item.
The benefit to this is that you don't have to modify your menu code per page, you modify the page itself, which you'll already be doing unless everything is fully dynamic.
It works like this:
<!-- ... head, etc ... -->
<body>
<ul class="nav">
<li>Home</li>
<li>Art</li>
<li>Contact</li>
</ul>
<!-- ... more page ... -->
</body>
Then you set up some CSS like this:
#NAV-HOME .nav-home,
#NAV-ART .nav-art,
#NAV-CONTACT .nav-contact { color:red; }
To change the "current" menu item, you can just assign the corresponding ID to an element higher in the document's structure. Typically I add it to the <body> tag.
To highlight the "Art" page, all you have to do is this:
<!-- The "Art" item will stand out. -->
<body id="NAV-ART">
<ul class="nav">
<li>Home</li>
<li>Art</li>
<li>Contact</li>
</ul>
<!-- ... more page ... -->
</body>
You can do this with CSS classes. For example, a selected class could identify the current shop, changing the color and outline. Then you can change the selection by adding/removing the class from the menu item.
Take a look here, it walks through a tutorial on building CSS menus.
Basically, it can't be done with CSS alone, some scripting would have to take place (server or client side, preferably server). As the others have suggested, add a 'selected' class (or something similar) to the active link, and define the styles for it in CSS.
For example, the links:
Eshop | Another eshop | Another eshop
The styles:
.selected {
font-weight:bold;
color:#efefef;
}
The links would be generated dynamically, using PHP for example:
<?php
foreach(array('eshop' => '#','another eshop' => '#','yet another eshop' => '#') as $title => $url) {
echo '<a href="' . $url . '"'
. ($url == $_SERVER['REQUEST_URI'] ? ' class="selected"' : null)
. '>' . $title . '</a>';
}
If you are moving to a new page in the same browser window, Zack Mulgrew and Bobby Jack both have excellent answers.
If you are opening the eshop link in a new window, there is not much you can do with css alone, and gs has a reasonable answer except for the choice of class name of (red).
Which is it?
As far as I know you can do this only by generating different code for every page (setting a different class for the current page) or by using JavaScript to change the menu after the page is loaded.
you could use and attribute selector like this...
a[href^="http:\\www.EShop"]:visted { color: red; }
By doing that you are saying any link that has a href that starts with http:\Eshop.com and has been visted apply this style.
It depends on how your pages are constructed, but the classic CSS was of doing this is with an id on the body, as well as each navigational link, so you might have something like:
eshop.html
<body id="eshop">
<ul>
<li>Eshop</li>
<li>Another eshop</li>
<li>Another eshop</li>
</ul>
</body>
and corresponding CSS:
#eshop #link-eshop, #aeshop, #link-aeshop, #eshop-three #link-eshop-three
{
color: red;
outline: 1px solid red;
}
the navigation is consistent; only the id on the body changes from page to page.

Resources