Nikson
Nikson

Reputation: 940

How to programmatically open an Accordion in Angular 4

I am working in an Angular 4 application in this I have the same accordion in two components .What I want to do is if a user clicked on the accordion from first component I want to get the index of the selected accordion and pass it to second component there I set the selected accordion to open and show the contents in it on page load (without click on it )

currently I have single accordion in first component ,If multiple accordion binds from API the selected index will changed dynamically.

Here is my code :

https://stackblitz.com/edit/angular-bootstrap-carousel-dynamic2-tsrt1w?file=app%2Fone%2Fone.component.html

Upvotes: 1

Views: 2894

Answers (1)

Nitishkumar Singh
Nitishkumar Singh

Reputation: 1839

You can pass id using route params, look into below sample codes for example:

one.component.html

<h5>One Component</h5>
<h6>Categories</h6>
<div class="accordion col-sm-12" id="accordion1" *ngFor='let data of dropdownData; let i=index'>
    <div class="accordion-group">

        <div class="accordion-heading">
            <a class="accordion-toggle h6" data-toggle="collapse"  routerLink="/two/{{i}}" data-parent="#accordion1" href="#collapseTwo + i">
                {{data?.CAMD_ENTITY_DESC}}
            </a>
        </div>
    </div>
</div>
<br>

app routes

const appRoutes: Routes = [
      {path:'one',component:OneComponent},
       {path:'two/:id',component:TwoComponent}]

two.component.ts

import { Component, OnInit, ViewChildren, QueryList, AfterViewInit, ElementRef } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { CartdataServiceService } from '../cartdata-service.service';
declare var $:any;
@Component({
  selector: 'app-two',
  templateUrl: './two.component.html',
  styleUrls: ['./two.component.css']
})
export class TwoComponent implements OnInit,AfterViewInit {
dropdownData: any;
id:string;

@ViewChildren('accordian') components:QueryList<ElementRef>;
constructor( private route: ActivatedRoute, private CartdataService: CartdataServiceService) {}
 ngOnInit() {
    this.CartdataService.get_New_Products().subscribe(
      data => {
        this.dropdownData = data;
          console.log(this.dropdownData);        
      });

       this.id = this.route.snapshot.paramMap.get('id');
  }

  ngAfterViewInit(){
    // print array of CustomComponent objects

    this.components.changes.subscribe(() => {
      let elem=this.components.toArray()[this.id];

      $(elem.nativeElement).trigger("click");

     console.log(elem);
  });
}

}

Now you can use id and select the required index for accordion.

Example Link

Upvotes: 2

Related Questions