Before, I use this simple script to create a simple accordion
(function() {
$('dl.accordion').on('click', 'dt', function() {
this_= $(this);
this_
.addClass("selected")
.next()
.slideDown(200)
.siblings('dd')
.slideUp(200);
this_.siblings()
.removeClass("selected")
});
})();
And this html
<dl class="accordion">
<dt>What are your hours?</dt>
<dd>We are open 24/7.</dd>
<dt>What are your hours?</dt>
<dd>We are open 24/7.</dd>
</dl>
Now I want to create a copy of this code written in Angular 2.
How can I create a simple acordion like above in Angular 2?
I guess I have to learn renderer, elementRef etc. Could you suggest other topics which I should learn to create this?
try this solution, this is very simple accordion:
app/accordion.component.ts
app/accordion-group.component.ts
app/app.component.ts
app/posts.service.ts
Online demo: https://plnkr.co/edit/xFBllK?p=preview
Document:
The Problem
The biggest thing to take away is knowing the "GetElementbyClassName" or "GetElementbyID" will not work unless it is being called within Angular 2. This is because the DOM will always load before Angular components loads thus there will never be an object to get a class or id from.
Solution
Angular has "Hooks" that you can tap into that will allow you to run code when a specific event happens, such as when component loads
ngAfterViewInit()
This can all be avoided by using directives to do your accordion but if you want to run your above javascript, then just run that in an
ngAfterViewInit()
function in yourexport class componentName {}
and it will work.Sample
Here is a sample where I did exactly what I stated above:
I don't know whether my solution is legal within angular, but I've come up with a simple accordion using a service.
Click here to check out solution on stackblitz