繁体   English   中英

如何使用angular 2在页面首次加载时将活动链接设置为默认链接

[英]How to set a active link as default when page first time load using angular 2

import {Component, Input, Output, EventEmitter, OnInit, AfterContentInit} from 'angular2/core';
import {FORM_DIRECTIVES, NgFor} from 'angular2/common';
import {MenuService} from './menu.service';
import {OrderByPipe} from '../shared/pipes/OrderBy';

declare var $: any;

@Component({
 selector: 'category',
 directives: [FORM_DIRECTIVES, NgFor],
 providers: [
    MenuService
 ],
 pipes: [OrderByPipe],
 template: `
    <div class="category-list" data-spy="affix" data-offset-top="20" id="nav2"> 
     <span class="category-list-item" *ngFor="#item of items | orderBy :['sort_order']"
        (click)="change(item)"
        [ngClass]="{'active':item.active}">
        <a id="elementID">{{item.name}}</a>
     </span>
 </div>

`
})

export class CategoryComponent implements OnInit, AfterContentInit {
@Input() items:any;
@Output('change') changeEmitter: EventEmitter<any> = new EventEmitter();

change(item:any): void {
    this.items.map((o:any)=> { o.active=false;});
    item.active = true;
    this.changeEmitter.emit(item);
    $('html, body').animate({
        scrollTop: 0// $('#elementID').offset().top + 200
    }, 300);
}
ngOnInit() {
    // this.items.map((o:Object)=> { o.active=false;});
    // this.items[0].active=true;
        $('#nav2').affix({
            offset: { top: 100 }
        });
}
ngAfterContentInit() {
            // Component content has been initialized
    // console.log(this.items);
  }
}


[![current behavior of nav link][1]][1]

导航链接的预期行为,它获取背景色,但仅在单击任何链接后

我在产品列表页面使用了angular 2。 我试图在单击后为链接提供背景色,并且工作正常,但问题是在第一次加载页面时,第一个链接应默认为bg颜色激活。

您可以在ngOnInit方法中使用它:

ngOnInit() {
  this.items.map((o:any)=> { o.active=false;});
  this.items[0].active = true;
}

不要忘了检查this.items是否未定义并且对应于数组...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM