2017-10-15 54 views
-2

請幫助需要。我試圖在父組件中點擊一個按鈕來加載父組件中的子組件。如何在單擊按鈕時加載兒童組件4

請提出建議。我給了它一個工作,但我真的很想知道這是否是合適的方法。實現如下:

<div class="btn-group" role="group"> 
     <button type="button" id="stars" class="btn btn-primary" data-toggle="tab" (click)="clickStars()"><span class="glyphicon glyphicon-star" aria-hidden="true"></span> 
     <div class="hidden-xs">Stars</div> 
     </button> 
    </div> 
    <div class="btn-group" role="group"> 
     <button type="button" id="favorites" class="btn btn-default" data-toggle="tab" (click)="clickFavorite()"><span class="glyphicon glyphicon-heart" aria-hidden="true"></span> 
     <div class="hidden-xs">Favorites</div> 
     </button> 
    </div> 
    <div class="btn-group" role="group"> 
     <button type="button" id="following" class="btn btn-default" data-toggle="tab" (click) = "clickFollowings()"><span class="glyphicon glyphicon-user" aria-hidden="true"></span> 
     <div class="hidden-xs">Following</div> 
     </button> 
    </div> 
    </div> 
    <div class="well"> 
    <div class="tab-content"> 
     <app-stars *ngIf="!starsHidden"></app-stars> 
     <app-favorites *ngIf="!favoriteHidden"></app-favorites> 
     <app-followings *ngIf="!followingsHidden"></app-followings> 
    </div> 
    </div> 
</div> 



import { Component, OnInit } from '@angular/core'; 

@Component({ 
    selector: 'app-profile', 
    templateUrl: './profile.component.html', 
    styleUrls: ['./profile.component.css'] 
}) 
export class ProfileComponent implements OnInit { 

    starsHidden:boolean; 
    favoriteHidden:boolean; 
    followingsHidden:boolean 

    constructor() { } 

    ngOnInit() { 
    this.starsHidden = false; 
    this.favoriteHidden = true; 
    this.followingsHidden = true; 
    } 

    clickStars(){ 
    this.starsHidden = false; 
    this.favoriteHidden = true; 
    this.followingsHidden = true; 
    } 

    clickFavorite(){ 
    this.starsHidden = true; 
    this.favoriteHidden = false; 
    this.followingsHidden = true; 
    } 

    clickFollowings(){ 
    this.starsHidden = true; 
    this.favoriteHidden = true; 
    this.followingsHidden = false; 
    } 

} 
+1

歡迎來到SO。本網站不是代碼編寫服務,不適用於提供完整的解決方案。用戶預計將表現出一定的努力和代碼,而SO是來幫助你解決沿途特定的編程問題。你有沒有嘗試過任何東西?請閱讀:https://stackoverflow.com/help/asking –

+0

對於代碼評論,最好問這裏:https://codereview.stackexchange.com/ –

回答

0

是的,這很好,但所有這些變量和方法看起來像一場噩夢。爲什麼不只是一個字符串的工作,例如:

activeTab: 'STARS' | 'FAVORITES' | 'FOLLOWINGS'; 

onChangeTab(tab: string){ 
    this.activeTab = tab; 
} 

你想你的模板改爲類似於這樣:

<button (click)="onChangeTab('STARS')">Stars</button> 

這將是罰款,但它會是更好如果你製作了自己的TabsComponent來管理所有的邏輯,並且無論你想要什麼,都可以輕鬆地重用它。

+0

嗨基督教,感謝您的建議。這是非常有幫助:) –