【问题标题】:Angular 4 : Cannot read property 'nativeElement' of undefinedAngular 4:无法读取未定义的属性“nativeElement”
【发布时间】:2018-07-17 04:28:31
【问题描述】:

我试图在加载组件时手动单击手风琴。但在我的情况下,我收到了标题中提到的控制台错误,并且手风琴也没有被点击。

手风琴:

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

}

谁能帮我解决这个问题。

【问题讨论】:

    标签: angular typescript viewchild


    【解决方案1】:

    如果你想触发点击而不点击,你可以使用 nativeElement.click

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

    【讨论】:

    • 您是否尝试针对任何特定元素?
    • 我只是想通过使用手风琴的索引位置@Chellappan 来点击手风琴
    • 好的@Chellappan
    • 我在这里发布的相同代码在 stackblitz 中工作,但不在我的项目中,请帮我解决这个问题stackblitz.com/edit/…@Chellappan
    • 在您的项目中,您现在遇到了什么错误?所以你是用jquery来触发函数的?
    猜你喜欢
    • 2019-03-17
    • 1970-01-01
    • 1970-01-01
    • 2021-07-09
    • 2018-02-26
    • 2017-12-15
    • 2017-09-28
    • 1970-01-01
    • 2018-03-20
    相关资源
    最近更新 更多