I am trying an implementation of accordion effect in one of my Angular views. The most basic accordion example you would find over at w3schools. Please take a look at this stackblitz url where I have tried to implement the same, using the same approach I used in my original project.
https://stackblitz.com/edit/stackblitz-starters-v54vdwmj
Nothing is working. What’s confusing is that there is no compilation error or runtime errors in the console which really doesn’t help at all. Had there been some sort of errors, it would have at least given me a pointer in some direction.
Can you get this accordion on stackblitz working?
Thanks!
2
Answers
Head over to
angular.dev
and read the documentation, that is best to start your angular journey!First accordion is going to repeat so it should be a separate component.
The content of the accordion, can be HTML, so we can use the angular concept
content projection
to project the content inside the accordion.We can listen for click event using
(click)
property binding and toggle a signal which tracks the open close state.The component will take an
input
signal, which is the title.We can use property binding
[title]
to pass in the title.Finally we use two directives
ngClass
andngStyle
to conditionally add the classes to the accordion.Full Code:
TS:
HTML:
Stackblitz Demo
A javascript based accordion use generally a css class.
You has define:
You need add some like
Well, another is that your function "accordianUtility" should be only execute one time. So use ngAfterViewInit in your component and remove the "accordianClicked".
your forked stackblitz
More. You should avoid add listeners using javascript, why not use some more simple an "Angular event"?
and your accordianClicked function in component reply the behaivour of the function in your "acordian-utily.ts
NOTE: Really it’s better pass to the function the "panel" as argument
NOTE2: Really I agree with Naren and JSON Derulo, your should use an "angular aproach". in ng-bootstrap you have a library with accordion, or you can use Bootstrap 5