【问题标题】:@ViewChild || native element Issue@ViewChild ||本机元素问题
【发布时间】:2021-05-18 15:53:48
【问题描述】:

我正在尝试使用基于 JavaScript 对象的 @ViewChild 访问 HTML div,如下所示:

<div class="main-div">
<gs-configuration-tabs ></gs-configuration-tabs>
<div class="content-div">
        <div class="pipelines" *ngFor = "let pipeline of pipelineData; let i = index">
            <div class="pipeline-block oxyclass" *ngIf ="pipeline?.oxy" #oxyBlock>
                <button class="pill" *ngIf = "pipeline?.oxy?.status == 'active'">Active</button>
                {{pipeline?.oxy?.name}}
            </div>
        </div>
</div>
</div>

TypeScript 代码:

@ViewChild('oxyBlock', {static: false}) oxyBlock: ElementRef;
@ViewChild('topicBlock', {static: false}) topicBlock: ElementRef;
@ViewChild('halBlock', {static: false}) halBlock: ElementRef;

ngAfterViewInit() {
    console.log("After View Init::",this.oxyBlock,this.halBlock);
    this.pipelineData.forEach(function(item) {
      console.log("Item data is::",item.oxy.role);
      if (item)
      {
        if (item.oxy.role == 'Publisher')
        {
          console.log('Oxy to HAL');
          const Line1 = new LeaderLine(this.oxyBlock.nativeElement,this.topicBlock.nativeElement);
          const Line2 = new LeaderLine(this.topicBlock.nativeElement,this.halBlock.nativeElement);
        }
        else{
          console.log('HAL to Oxy');
          const Line1 = new LeaderLine(this.halBlock.nativeElement,this.topicBlock.nativeElement);
          const Line2 = new LeaderLine(this.topicBlock.nativeElement,this.oxyBlock.nativeElement);
        }
      }
    });
    
    // const Line1 = new LeaderLine(this.oxyBlock.nativeElement,this.topicBlock.nativeElement);
    // const Line2 = new LeaderLine(this.topicBlock.nativeElement,this.halBlock.nativeElement);
  }

我使用leader-line在基于JavaScript Object的div之间绘制箭头。在 foreach 循环之外一切正常。但是,在循环内我面临以下错误:

TypeError: 无法读取未定义的属性“oxyBlock”

【问题讨论】:

    标签: javascript arrays angular typescript


    【解决方案1】:

    在您对forEach() 的回调中,您使用this。您认为它指的是组件,但事实并非如此。如果您将this 登录到控制台,您可以很容易地看到这一点。或者您可以使用调试器并在回调中设置断点。

    您需要使用箭头函数来正确捕获this的值。

    ngAfterViewInit() {
        this.pipelineData.forEach(item => {
    

    【讨论】:

      猜你喜欢
      • 2020-03-07
      • 1970-01-01
      • 2019-08-29
      • 2016-11-04
      • 2019-01-20
      • 1970-01-01
      • 1970-01-01
      • 2017-03-03
      • 2018-02-12
      相关资源
      最近更新 更多