2017-10-20 98 views
0

我有一个标签导航元素有两个选项卡,它需要显示一个基于哪个选项卡被点击并隐藏其他组件的组件。如果点击的选项卡已经“激活”,则该组件需要保持显示。切换两个元素之间的显示和隐藏

我有这个工作,但它似乎对我非常低效。任何人都可以告诉我一个更好的方法来做到这一点

下面是我现在设置的方法。为了不在问题中发布每个文件,请了解该项目的设置是否正确。

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div> 
     <button type="button" (click)="changeShowStatus(oneShowing=true,twoShowing=false)">1</button> 
     <button type="button" (click)="changeShowStatus(twoShowing=true,oneShowing=false)">2</button> 
     <div class="box1" *ngIf="oneShowing"> 
     <p>some content</p> 
     </div> 
     <div class="box2" *ngIf="twoShowing"> 
     <p>some content2</p> 
     </div> 
    </div> 
    `, 
}) 
export class App { 
    name:string; 
    oneShowing:boolean; 
    twoShowing:boolean 

    constructor() { 
    this.oneShowing = true; 
    this.twoShowing = false 
    } 
} 

Plunker

回答

0

@Component({ 
 
    selector: 'my-app', 
 
    template: ` 
 
    <div> 
 
    <button type="button" (click)="activeIndex = 1">1</button> 
 
    <button type="button" (click)="activeIndex = 2">2</button> 
 
    <div class="box1" *ngIf="activeIndex === 1"> 
 
    <p>some content</p> 
 
    </div> 
 
    <div class="box2" *ngIf="activeIndex === 2"> 
 
    <p>some content2</p> 
 
    </div> 
 
</div> 
 
    `, 
 
}) 
 
export class App { 
 
    activeIndex = 0; 
 

 
    constructor() { 
 
    } 
 
}

0

这里做另一种方式。

1.初始化currentContent变量为默认内容值。

2.点击一个按钮将其值设置为期望的内容。

3.如果currentContent匹配desiredValue,则显示div。

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div> 
     <button type="button" (click)="currentContent='content1'">1</button> 
     <button type="button" (click)="currentContent='content2'">2</button> 
     <div class="box1" *ngIf="currentContent==='content1'"> 
     <p>some content</p> 
     </div> 
     <div class="box2" *ngIf="currentContent==='content2'"> 
     <p>some content2</p> 
     </div> 
    </div> 
    `, 
}) 
export class App { 
    name: string; 
    currentContent: string = "content1"; //default tab 

    constructor() { 

    } 
} 
0

另一种方法是使用brodcasting事件。在这里创建一个可观察的brodcaster和brodcast消息,在任何一个弹出窗口即将打开时关闭其他弹出窗口。 https://blog.lacolaco.net/post/event-broadcasting-in-angular-2/在网页上存在多个日期选择器或下拉列表时需要使用它,并且需要一次打开一个日期选择器或下拉列表。我使用它,非常有助于制作评论类型的下拉列表。