Reputation: 643
I am working in Angular 7 Application where
Goal:-
My goal is to display more then one child components in parent component in such a way that only one child component is displayed at a time and next child component displays after clicking on previous child component
example :-
<parent component>
<h1>dummy text</h1>
<child component1 *ngIf='c1' (click)='displayc2()'> </child component1>
<child component2 *ngIf='c2'> </child component2>
<child component3 *ngIf='c3'> </child component3>
<child component4 *ngIf='c4'> </child component4>
<parent component>
My way of doing it
Here only child component1 is displayed when page will load so I took
c1 = true;
c2 = false;
c3 = false;
c4 = false;
and on clicking component child 1 component I am calling function
displayc2() {
this.c2 = true;
this.c1 = false;
this.c3 = false;
this.c4 = false;
}
So here I have to write new function again and again to define condition true for displaying each child component.
I am sure there is far better way this is a very tedious and boring way on solving this type of problem , so please correct me or suggest a better way to solve the problem
Upvotes: 0
Views: 1391
Reputation: 1778
<parent component>
<h1>dummy text</h1>
<child component1 *ngIf='c1 === 1' (click)='c1 = 2'> </child component1>
<child component2 *ngIf='c1 === 2' (click)='c1 = 3'> </child component2>
<child component3 *ngIf='c1 === 3' (click)='c1 = 4'> </child component3>
<child component4 *ngIf='c1 === 4' (click)='c1 = 1'> </child component4>
<parent component>
// In TS:
c1 = 1;
Upvotes: 0
Reputation:
I won't criticize or ask you why you're doing it this way, but there are more suited solutions to your issue.
Other than that, consider using a counter :
<parent component>
<h1>dummy text</h1>
<ng-container *ngFor="let i of [0, 1, 2, 3, 4]">
<child
[componentNumber]="i"
*ngIf="i === counter"
(click)="counter = counter + 1"></child component2>
</ng-container>
<parent component>
With this, your code gets simplified, and more importantly, totally dynamic. You can create 600 components, all you have to do is change the array inside ngFor
!
Upvotes: 1