I have a simple problem, but I'm a beginner so I can't understand the logic,
I have 2 buttons one and two, when I click on one I would like to display instead of one and two the other buttons so three and four? made a switch.
What is the best way to do this? Is using if else in the HTML correct or should we move this logic to the ts file?
Thanks in advance.
html
<div *ngIf="!isButtons">
<button> one</button>
<button> two</button>
</div>
<div>
<button> three</button>
<button> four</button>
</div>
ts.file
isButtons:boolean = false;
CodePudding user response:
The logic is simple enough to remain in the template, you don't need any more code in your component. A simple (click)
and a <ng-template>
will do the trick:
<div *ngIf="!isButtons; else threeAndFour">
<button (click)="isButtons=true"> one</button>
<button> two</button>
</div>
<ng-template #threeAndFour>
<div>
<button> three</button>
<button> four</button>
</div>
</ng-template>
CodePudding user response:
Given your code example, you can just
- add
*ngIf="isButtons"
to the seconddiv
so you'll handle the final state - add the click handler on the button you want to trigger the change:
(click)="isButtons = true"
Final snippet:
<div *ngIf="!isButtons">
<button (click)="isButtons = true"> one</button>
<button> two</button>
</div>
<div *ngIf="isButtons">
<button> three</button>
<button> four</button>
</div>
Jeremy Thille's answer is just as good, but most likely not something a beginner can handle (ng-template
and more complex *ngIf
usage).