角4:无法读取未定义的属性'nativeElement'

时间:2018-07-17 04:28:31

标签: angular typescript viewchild

加载组件时,我试图手动单击手风琴。但是,在我的情况下,出现标题中提到的控制台错误,手风琴也未单击。

手风琴:

<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"    data-parent="#accordion1" href="#collapseTwo + i" #accordion>
                {{data?.CAMD_ENTITY_DESC}}
            </a>
        </div>

        <div *ngFor='let group of data.group; let j=index' id="collapseTwo + i" class="accordion-body collapse"
         style="margin-left:10px">
            <div class="accordion-inner">
                <div class="accordion" id="accordion2">
                    <div class="accordion-group">

                        <div class="accordion-heading">
                            <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" [href]="'#collapseInnerTwo' + j">
                                {{group?.CAMD_PRGRP_DESC}}
                            </a>
                        </div>

                        <div [id]="'collapseInnerTwo' + j" class="accordion-body collapse" style="margin-left:10px;margin-top:3px">

                            <div class="accordion-inner" *ngFor='let subgroup of group?.subgroup; let i=index'>
                                {{subgroup?.CAMD_PRSGRP_DESC}}
                            </div>
                        </div>

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

在这里,我已给出 #accordion 来获取elementRef。

组件

export class TwoComponent implements OnInit, AfterViewInit {
  dropdownData: any;
  id: number = 0;

  @ViewChildren('accordion') a: QueryList<ElementRef>;

  constructor(private route: ActivatedRoute, private CartdataService: CartdataServiceService) { }

  ngOnInit() {
    this.CartdataService.get_New_Products().subscribe(
      data => {
        this.dropdownData = data;
      });
  }

  ngAfterViewInit() {
    this.a.changes.subscribe(() => {
      let elementRef = this.a.toArray()[this.id];
      $(elementRef.nativeElement).trigger("click");
    });
  }

}

任何人都可以帮助我解决此问题。

1 个答案:

答案 0 :(得分:1)

如果要触发单击而不单击,请使用nativeElement.click

ngAfterViewInit() {
    this.a.changes.subscribe(() => {
      let elementRef = this.a.toArray()[this.id];
       this.a.nativeElement.click;
    });
  }
}