我正在使用Angular 4应用程序,我有两个组件中的同一个手风琴。我想要做的是如果用户从第一个组件点击手风琴我想获得所选手风琴的索引并通过它到第二个组件我设置选定的手风琴打开并在页面加载时显示其中的内容(不点击它)
目前我在第一个组件中有单手风琴,如果多个手风琴从API绑定,所选索引将动态更改。
这是我的代码:
答案 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选择所需的索引。