如何在单击按钮时加载儿童组件4
问题描述:
请帮助需要。我试图在父组件中点击一个按钮来加载父组件中的子组件。如何在单击按钮时加载儿童组件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;
}
}
答
是的,这很好,但所有这些变量和方法看起来像一场噩梦。为什么不只是一个字符串的工作,例如:
activeTab: 'STARS' | 'FAVORITES' | 'FOLLOWINGS';
onChangeTab(tab: string){
this.activeTab = tab;
}
你想你的模板改为类似于这样:
<button (click)="onChangeTab('STARS')">Stars</button>
这将是罚款,但它会是更好如果你制作了自己的TabsComponent来管理所有的逻辑,并且无论你想要什么,都可以轻松地重用它。
+0
嗨基督教,感谢您的建议。这是非常有帮助:) –
欢迎来到SO。本网站不是代码编写服务,不适用于提供完整的解决方案。用户预计将表现出一定的努力和代码,而SO是来帮助你解决沿途特定的编程问题。你有没有尝试过任何东西?请阅读:https://stackoverflow.com/help/asking –
对于代码评论,最好问这里:https://codereview.stackexchange.com/ –