How to apply style in angular6 - css

I want to apply text color when expected id will clicked
<nav class="navbar ">
<ul class="navbar-nav">
<li *ngFor="let item of items">
<a class="nav-link" >{{item.title}}</a>
</li>
</ul>
</nav>
items=[{id:1,title:"a"},{id:2,title:"b"},{id:2,title:"c"},{id:3,title:"d"}]
controller-
private name;
this.routes.params.subscribe((params)=>{
this.data=params['id'];
console.log(this.data);
})
this.Service.getAllItems().subscribe((data)=>{
this.items=data;
for(let i of this.items){
if(i.id == this.data){
this.name=i.title;
}
}
For clicked id I have to apply text color red.How to apply it.Please help

You could have a variable with the active id, which is set when you click:
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
public activeId;
setIdActive(id) {
this.activeId = id;
}
}
And in your html:
<nav class="navbar ">
<ul class="navbar-nav">
<li *ngFor="let item of items">
<a (click)="setIdActive(item.id)" class="nav-link" [ngClass]="{'apply-color': item.id == activeId}" >{{item.title}}</a>
</li>
</ul>
</nav>
apply-color it's a class with the color you want

This answer caters to condition where we need to highlight all the options which are clicked
If you want to change the color of all the links which are clicked and not just the last one, I advise you to use a HostListener directive.
consructor(privte elem: ElementRef, private renderer: Renderer) { }
#HostListener('click',['$event']) //in your case, the event parameter can be omitted
Click(event: Event) {
this.renderer.setElementStyle(elem.nativeElement, 'color', 'red');
}
And if just the CSS style for a:visited works for you (not tried by myself), it would be the best solution

You can you [ngClass] for this problem. When you click the link pass the item to the function. this will change the activeId. By using [ngClass] the class will apply to the link.
let activeId:number;
makeALinkActive(item){
this.activeId = item.id;
}
items=[{id:1,title:"a"},{id:2,title:"b"},{id:2,title:"c"},{id:3,title:"d"}]
.red{
color: red;
}
<nav class="navbar ">
<ul class="navbar-nav">
<li *ngFor="let item of items">
<a class="nav-link" [ngClass]="{'red':activeId === item.id}" (click)='makeALinkActive(item)'>{{item.title}}</a>
</li>
</ul>
</nav>
items=[{id:1,title:"a"},{id:2,title:"b"},{id:2,title:"c"},{id:3,title:"d"}]

Related

Menu: animation open/close

When I open and close a menu item, there is no animation. I would like to know how to create an animation, please?
HTML file
<div class="wrapper">
<!-- Top Menu -->
<div class="sidebar">
<!-- Menu Item -->
<ul>
<li
*ngFor="let menu of menus; let i = index"
[class.active]="menu.active"
>
<ng-container>
<a class="item" (click)="selectMenu(menu)">
<i [class]="menu.iconClass"></i> {{ menu.name }}
<i class="fa fa-chevron-down"></i>
</a>
<ul *ngIf="menu.active">
<li *ngFor="let submenu of menu.submenu" class="submenu">{{submenu.name}}</li>
</ul>
</ng-container>
</li>
</ul>
</div>
</div>
I don't know if it's possible to do it in Angular or CSS? I made you a reproduction of the project => Stackblitz.
the easer is using Angular animations. add this animation to your component
animations:[
trigger('accordion', [
transition(':enter', [
style({ height: 0 }),
animate('1000ms', style({ "height": '*' })),
]),
transition(':leave', [
animate('100ms', style({ "height": 0 }))
])
]),
]
See that, when "enter" start with style:height=0 and animate to reach style:height=* (the * main that reach the "normal" height) and you use "leave" to animate and change the style to "height=0".
Then just use
<ul #accordion *ngIf="menu.active">
<li *ngFor="let submenu of menu.submenu" class="submenu">
{{submenu.name}}
</li>
</ul>
NOTE1: don't forget import the BrowserAnimationsModule in your module
NOTE2: You need add to your .css
.wrapper ul li ul{
overflow:hidden;
}
Your forked stackblitz
I think you should change app.component.ts like this.
selectMenu(parentMenu: { name: string, active:boolean }): void {
this.menus.forEach((menu) => {
if (menu.name === parentMenu.name) {
menu.active = !menu.active;
}
});
}
}
because Each time active is pressed, the boolean value should change.
have a nice day:)

How to highlight same page number for two different URLs in angular 2 using routerLink

I have pagination like below. I would like to highlight page number 2 for both the below links.
[routerLink]="['/link/sublink2']
[routerLink]="['/link/sublink22']
How to achieve this using angular 2.
<ul class="pagination pagination-plain">
<li [routerLinkActive]="['active']">
<a [routerLink]="['/link/sublink1']">1</a>
</li>
<li [routerLinkActive]="['active']">
<a [routerLink]="['/link/sublink2']">2</a>
</li>
<li [routerLinkActive]="['active']">
<a [routerLink]="['/link/sublink3']">3</a>
</li>
</ul>
In your html,
<li [class]="addActiveClass()" >
<a [routerLink]="['/link/sublink2', '/link/sublink22']">2</a>
</li>
and in your component.ts file,
private addActiveClass() {
let fullpath:any[]=this.router.url.split("/")
if(fullpath[2] == 'sublink2' || fullpath[2] == 'sublink22'){ /* fullpath[2] has the second parameter after the '/'. If you want first parameter after the slash, use fullpath[1] */
return 'active';
}else{
return '';
}
}
This adds an active class to the li when you route to the page. You can highlight the li.active using css.

Change browserHistory.push('/login') form v2 to alternative in React Router V4

In this tutorial on Meteor and React an author uses react-router v2-3, I want to do it using new React- router v4. So I try to change this code, that used react-router v2:
import React from 'react';
import { IndexLink, Link, browserHistory } from 'react-router';
export class Navigation extends React.Component {
logout(e) {
e.preventDefault();
Meteor.logout(function() {
browserHistory.push('/login');
});
}
render() {
return (
<nav className="navbar navbar-default">
<div className="container-fluid">
...
<div className="collapse navbar-collapse" id="main-nav">
<ul className="nav navbar-nav">
<li><IndexLink to="/" activeClassName="active">Dashboard</IndexLink></li>
<li><a href="#" onClick={this.logout}>Logout</a></li>
</ul>
</div>
</div>
</nav>
)
}
}
to this one, that uses v4:
import React from 'react'
import { NavLink } from 'react-router-dom'
export class Navigation extends React.Component {
logout(e){
e.preventDefault()
Meteor.logout(function () {
this.context.history.push('/login')
})
}
render () {
return (
<nav className='navbar navbar-default'>
<div className='container-fluid'>
...
<div className="collapse navbar-collapse" id="main-nav">
<ul className="nav navbar-nav">
<li><NavLink to="/" activeClassName="active">Dashboard</NavLink></li>
<li><NavLink to="/logout" activeClassName="active"
onClick={this.logout.bind(this)}>Logout</NavLink></li>
</ul>
</div>
</div>
</nav>
)
}
}
but browser console.logs me an error:
Do you have /logout path in your app? I'm asking because you're probably handling that using logout method passed into onClick prop.
If you look how <Link> is working
https://github.com/ReactTraining/react-router/blob/v4.0.0-beta.8/packages/react-router-dom/modules/Link.js
You can see if there is a prop called onClick component will call that function with event parameter and if event hasn't set defaultPrevented to true <Link> will try to go to /logout path

Angular 2 change css by id

I'm trying to change the menu css that was clicked by id, and when click on another menu all others lose their style, and only what was clicked wins the style.
But I'm not making to do this, someone could help me?
import { Component } from '#angular/core';
import { NgClass } from '#angular/common';
#Component({
selector: 'my-header',
template: `
<nav class="navbar navbar-default navbar-static-top">
<ul class="nav navbar-nav">
<li><a [ngClass]="{'selectedClass': selected}" (click)="selectId($event)" id="1">Menu 1</a></li>
<li><a [ngClass]="{'selectedClass': selected}" (click)="selectId($event)" id="2">Menu 2</a></li>
<li><a [ngClass]="{'selectedClass': selected}" (click)="selectId($event)" id="3">Menu 3</a></li>
<li><a [ngClass]="{'selectedClass': selected}" (click)="selectId($event)" id="4">Menu 4</a></li>
</ul>
</nav>
`,
styles: [`
.selectedClass {
color: #cc0000;
background-color: #ffffff;
}
`]
})
export class HeaderComponent {
selected = false;
selectId(event) {
console.log(event.currentTarget.id);
selected = true;
}
}
Well, at the moment you're just setting selected (edit: you forget this. in front of your selected btw, just saw that now) to true every time one of your links is clicked so on your first click all of your items get the class selectedClass and after that nothing else changes anymore.
Without modifying your example too much, you could just pass and save an id of your latest clicked item instead of a boolean value. Then just check on the selected id if the item should have selectedClass.
Something like this:
<ul class="nav navbar-nav">
<li><a [ngClass]="{'selectedClass': selected == 1}" (click)="selectId(1)">Menu 1</a></li>
<li><a [ngClass]="{'selectedClass': selected == 2}" (click)="selectId(2)">Menu 2</a></li>
<li><a [ngClass]="{'selectedClass': selected == 3}" (click)="selectId(3)">Menu 3</a></li>
<li><a [ngClass]="{'selectedClass': selected == 4}" (click)="selectId(4)">Menu 4</a></li>
</ul>
export class HeaderComponent {
selected: number;
selectId(id: number) {
this.selected = id;
}
}
A better approach would probably be to use defined objects for your navigation items in the first place so you don't have to worry about which values to pass / check for something like this and make it more dynamic.
For example you could define your links directly in your class (or even via #Input()), let *ngFor build up your navigation and pass around the "navigation item objects" directly:
export class HeaderComponent {
#Input() navigationItems: any[] = [ // defined a default array as example
{
text: 'Menu 1',
selected: false
}
];
onItemClick(item: any) {
this.navigationItems.map((navItem) => {
navItem.selected = navItem === item;
});
}
}
<ul class="nav navbar-nav">
<li *ngFor="let item of navigationItems">
<a [ngClass]="{'selectedClass': item.selected}"
(click)="onItemClick(item)">
{{item.text}}
</a>
</li>
</ul>

How to change the color of a link on hover of an another link?

Here's a code
<a id="link1" href="#" >About</a>
<a id="link2" href="#">Contact us</a>
I want the link1's color to be changed when link2 is hovered.
Is it possible with css?.
Since CSS does not seem to be able to handle this, try JavaScript
window.onload=function() {
document.getElementById("link2").onmouseover=function() {
document.getElementById("link1").style.color="red";
}
document.getElementById("link2").onmouseout=function() {
document.getElementById("link1").style.color="blue";
}
}
<a id="link1" href="#" >About</a>
<a id="link2" href="#">Contact us</a>
Or using siblings
function prevSib(elem) {do { elem = elem.previousSibling;} while ( elem && elem.nodeType !== 1 ); return elem; }
window.onload=function() {
document.getElementById("link2").onmouseover=function() {
prevSib(this).style.color="red";
}
document.getElementById("link2").onmouseout=function() {
prevSib(this).style.color="blue";
}
}
<a id="link1" href="#" >About</a>
<a id="link2" href="#">Contact us</a>
Using pure css it is not possible go backward. You can go in cascading ways.
But, you can do it with JQuery. like:
$(document).ready(function(){
$(".link2").mouseover(function(){
$(".link1").css("color", "red");
});
$(".link2").mouseout(function(){
$(".link1").css("color", "black");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="link1" class="link1" href="#" >About</a>
<a id="link2" class="link2" href="#">Contact us</a>
Hope it helps.
CSS can't select the previous siblings. You can use JavaScript:
var links = [].slice.call(document.querySelectorAll('.menu_item'));
function hover(event) {
var pre = this.previousElementSibling,
method = event.type === 'mouseenter' ? 'add' : 'remove';
if (pre) {
pre.classList[method]('active');
}
}
links.forEach(function(el) {
el.addEventListener('mouseenter', hover);
el.addEventListener('mouseleave', hover);
});
The above code assumes that the a elements have class of menu_item and class of active should be added to the previous sibling of the hovered element.
Here is a demo.
Use JavaScript to do that( link1's color to be changed when link2 is hovered ). You need to use html tag attributes like onmouseover and onmouseout.
Try this code. For changing color of link1 when link2 is hovered.
<html>
<head>
<script>
function colorchange(){
document.getElementById("link1").style.color="red";
}
function colorchange2(){
document.getElementById("link1").style.color="blue";
}
</script>
</head>
<body>
<a id="link1" href="#" >About</a>
<a id="link2" onmouseover="colorchange()" onmouseout="colorchange2()" href="#">Contact us</a>
</body>
</html>
I suppose this is what are you looking for.
First you need to wrap your links inside a container like this
<div class='container'>
<a id="link1" href="#" >About</a>
<a id="link2" href="#">Contact us</a>
</div>
and then apply this styles
.container:hover a:not(:hover){
color:red;
}
css only demo here
UPDATE
As I said in may comment bellow I supposed you wanted to change the style of all unhovered links, however if you want to change only link1 when link2 is hovered , but not change style of link2 when link1 is hovered you could write you css like this
second demo
.container:hover a:first-child:not(:hover){
color:red;
}

Resources