简体   繁体   中英

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]

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

I am using angular 2 for product listing page. I am trying to give background color to the link after clicking and it is working fine but the problem is when first time page is loaded, the first link should be default active with bg color.

You could use this in the ngOnInit method:

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

Don't forget to check that this.items isn't undefined and corresponds to an array...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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