如何以编程方式在Angular 4中打开手风琴

时间:2018-06-04 09:42:37

标签: html angular typescript bootstrap-4

我正在使用Angular 4应用程序,我有两个组件中的同一个手风琴。我想要做的是如果用户从第一个组件点击手风琴我想获得所选手风琴的索引并通过它到第二个组件我设置选定的手风琴打开并在页面加载时显示其中的内容(不点击它)

目前我在第一个组件中有单手风琴,如果多个手风琴从API绑定,所选索引将动态更改。

这是我的代码:

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

1 个答案:

答案 0 :(得分:1)

您可以使用route params传递id,请查看下面的示例代码:

<强> 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>

应用路线

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);
  });
}

}

现在您可以使用id并为accordion选择所需的索引。

Example Link