簡體   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