我有3个按钮和3个组件,我想要的是,最初只有第一个元素可见。单击按钮将显示相关组件并隐藏不相关的组件。你会怎么做?
@Component({
selector: 'Parent',
template: `
<div class="tab">
<span class="btn">show child 1</span>
<span class="btn">show child 2</span>
<span class="btn">show child 3</span>
</div>
<Child1></Child1>
<Child2></Child2>
<Child3></Child3>
`,
})
export class ParentComponent {
}
答案 0 :(得分:8)
@Component({
selector: 'Parent',
template: `
<div class="tab">
<span (click)="show('show1')" class="btn">show child 1</span>
<span (click)="show('show2')" class="btn">show child 2</span>
<span (click)="show('show3')" class="btn">show child 3</span>
</div>
<div *ngIf="show1"><Child1></Child1></div>
<div *ngIf="show2"><Child2></Child2></div>
<div *ngIf="show3"><Child3></Child3></div>
`
})
export class ParentComponent {
public show1 = true;
public show2 = false;
public show3 = false;
show(tab){
this.show1 = false;
this.show2 = false;
this.show3 = false;
console.log(tab)
if(tab == 'show1') {
this.show1 = true
}
if(tab == 'show2') {
this.show2 = true
}
if(tab == 'show3') {
this.show3 = true
}
}
}
非常粗糙的形式。根据需要优化代码。 但是,希望你有这个主意。
答案 1 :(得分:2)
第一个选择是,我会说最好使用延迟加载来解决此问题。 Angular Lazy loading。
如果您不想使用延迟加载并希望遵循Ajey的回答,则可以按照这种方式编写更少的代码
@Component({
selector: "Parent",
template: `
<div class="tab">
<span (click)="curStep = 'step1'" class="btn">show child 1</span>
<span (click)="curStep = 'step2'" class="btn">show child 2</span>
<span (click)="curStep = 'step3'" class="btn">show child 3</span>
</div>
<div *ngIf="curStep == 'step1'"><child1></child1></div>
<div *ngIf="curStep == 'step2'"><child2></child2></div>
<div *ngIf="curStep == 'step3'"><child3></child3></div>
`
})
export class ParentComponent {
curStep: string = "step1";
}