3

I have 3 buttons and 3 components, What I want is, initially, only the first element visible. Clicking the buttons will show relevant component and hide the not relevant. How would you do that?

@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  {
}
1

2 Answers 2

11
@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
        }
    }
}

Very crude form. Optimise the code as you like. But, hope you got the idea.

Sign up to request clarification or add additional context in comments.

2 Comments

Why Downvote ? according to question seems answer is correct
Downvoter, please try to explain or give a better solution.
2

The first option is I will say its better to use lazy loading to solve this problem. Angular Lazy loading.

If you don't want to use lazy loading and want to follow the answer from Ajey, you may follow this way to write less code

  @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";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.