2017-10-20 94 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/在網頁上存在多個日期選擇器或下拉列表時需要使用它,並且需要一次打開一個日期選擇器或下拉列表。我使用它,非常有助於製作評論類型的下拉列表。