当页面第一次使用角度2加载时,如何将活动链接设置为默认值

时间:2016-05-27 13:47:11

标签: javascript typescript angular

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]

Expected behavior of nav link, it is getting background color but only after clicking on any of the link

我在产品列表页面使用角度2。我试图在点击后给链接提供背景颜色,它工作正常,但问题是当第一次加载页面时,第一个链接应该是默认活动的bg颜色。

1 个答案:

答案 0 :(得分:1)

您可以在ngOnInit方法中使用此功能:

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

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