子组件:html
<ul>
<li *ngFor="let item of menus;let ind = index;">
<a href="#"
(click)="handelSelected(ind)"
[ngStyle]="{'color' : currentTab===ind ? titleActiveColor : titleColor}"
>
{{item.title}}
</a>
<span class="indicator" *ngIf="currentTab === ind"></span>
</li>
</ul>
css:
ul {
margin: 0 ;
padding: 0;
display: flex;
flex-direction: row;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
}
ul li{
white-space: nowrap;
margin: 0 5px;
padding: 0;
display: flex;
flex-direction: column;
}
a{
text-decoration: none;
}
::-webkit-scrollbar{
display: none;
}
.indicator{
height: 2px;
width: 2rem;
margin-top: 2px;
display: inline-block;
background-color: brown;
}
ts:
import { Component, OnInit,Input,Output,EventEmitter } from '@angular/core';
export interface TopMenu{
title:string,
link:string
}
@Component({
selector: 'app-nav-bar',
templateUrl: './nav-bar.component.html',
styleUrls: ['./nav-bar.component.css']
})
export class NavBarComponent implements OnInit {
currentTab = 0;
titleActiveColor = "red";
titleColor = "#000";
@Input() menus:TopMenu[]=[];
@Output() selectedIndex = new EventEmitter();
constructor() { }
ngOnInit() {
}
handelSelected(ind:number){
this.currentTab = ind;
this.selectedIndex.emit(this.menus[this.currentTab])
}
}
父组件:
html
<!--The content below is only a placeholder and can be replaced.-->
<app-nav-bar
[menus]="menu"
(selectedIndex)="handelSelectTab($event)"
></app-nav-bar>
ts:
import { Component } from '@angular/core';
import { TopMenu } from './components';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'navNg';
menu:TopMenu[]=[
{
title:'热门',
link:''
},
{
title:'男装',
link:''
},
{
title:'百货',
link:''
},
{
title:'运动',
link:''
},
{
title:'手机',
link:''
},
{
title:'家纺',
link:''
},
{
title:'食品',
link:''
},
{
title:'电器',
link:''
},
{
title:'鞋包',
link:''
},
{
title:'汽车',
link:''
},
{
title:'水果',
link:''
},
{
title:'电脑',
link:''
},
{
title:'内衣',
link:''
},
{
title:'家装',
link:''
},
{
title:'母婴',
link:''
},
{
title:'美妆',
link:''
},
{
title:'家具',
link:''
}
];
handelSelectTab(currentIndex:TopMenu){
console.log(currentIndex)
}
}
git地址:https://github.com/yyk316507/angualr8-demo