angular 2 - 如何切换classname

时间:2017-01-18 08:17:48

标签: angular

我有这个标签和面板组件。它现在工作得很好。但是现在,无论我单击哪里,只有第一个选项卡会有活动类。我想将active类名称提供给单击的选项卡。未单击的选项卡将不具有active类名。你会怎么做

@Component({
    template: `
        <div class="topicCreator">
            <ul class="nav nav-tabs">
                <li role="presentation" class="nav-item active" (click)="show('showDiscussion')">
                    <a class="nav-link active">Discussion</a>
                </li>
                <li role="presentation" class="nav-item" (click)="show('showEvent')">
                    <a class="nav-link">Event</a>
                </li>
                <li role="presentation" class="nav-item" (click)="show('showPoll')">
                    <a class="nav-link">Poll</a>
                </li>
            </ul>
            <CreateDiscussion *ngIf="showDiscussion"></CreateDiscussion>
            <CreatePoll *ngIf="showPoll"></CreatePoll>
            <CreateEvent *ngIf="showEvent"></CreateEvent>
        </div>
    `,
    styleUrls: ['./topicCreator.scss']
})
export class TopicCreatorComponent implements OnInit, AfterViewInit {

    public showDiscussion = true;
    public showPoll = false;
    public showEvent = false;

    show(tab){
        this.showDiscussion = false;
        this.showPoll = false;
        this.showEvent = false;

        if(tab == 'showDiscussion') {
            this.showDiscussion = true
        }
        if(tab == 'showPoll') {
            this.showPoll = true
        }
        if(tab == 'showEvent') {
            this.showEvent = true
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您可以使用class.active输入,如下所示

 <ul class="nav nav-tabs">
       <li role="presentation" class="nav-item" [class.active]="showDiscussion" (click)="show('showDiscussion')">
             <a class="nav-link">Discussion</a>
        </li>
        <li role="presentation" class="nav-item" (click)="show('showEvent')" [class.active]="showEvent">
             <a class="nav-link">Event</a>
        </li>
        <li role="presentation" class="nav-item" (click)="show('showPoll')" [class.active]="showPoll">
             <a class="nav-link">Poll</a>
        </li>
 </ul>