首页 > 解决方案 > 组件的构造函数调用了两次

问题描述

所以我有这个子组件,其中id属性是随机设置的:

export class FileSelectionComponent implements AfterViewInit {
  public type = 'app-file-selection';
  public id = 'FileSelection#' + Math.random().toString(16).slice(2, 8);
  @Input() jspinst: any;
  public x;
  public y;
  public selected_file: string;

  constructor(public dialog: MatDialog, private httpClient: HttpClient) {
    this.selected_file = '';
    console.log('constructor called');
    console.log(this.id);
  }
  ngAfterViewInit() {
    ...
    this.jspinst.addEndpoint(this.id, { anchor: 'Right'}, Endpoint1);
    this.jspinst.addEndpoint(this.id, { anchor: 'Left'}, Endpoint2);
    this.jspinst.draggable(this.id);
  }
}

父组件是这样的:

export class FlowComponent implements OnInit, AfterViewInit, OnChanges {
 public nodes: Array<any>;
 public jspl;

  constructor() {
    this.nodes = [];
    this.jspl = jsPlumb.getInstance();
  }

  addNode(type) {
        let nn = new FileSelectionComponent();
        this.nodes = this.nodes.concat([nn]);
        s = this.nodes;
        console.log('object created and added');
  }

  ngAfterViewInit() {
    s = this.nodes;
    this.jspl.bind('connection', function (info) {
      console.log(info.sourceId+' ----> '+info.targetId); //this output
      console.log(s[0].id+' ----> '+s[1].id); // and this output are not the same while they should
      console.log(Object.keys(s[0]));
      console.log(Object.values(s[0]));
    });
  }
}

当我点击一个按钮时,addNode方法被调用,你可以猜到,它的构造函数FileSelectionComponent被调用了两次,生成了两个不同的 id,这使得我无法在connection事件触发时检索相关节点。我发现了一些类似的问题但没有一个帮助:

  1. 我的按钮type="button"上有一个
  2. 我没有引导父组件和子组件,实际上我没有引导它们中的任何一个,我已经检查过app.module.ts(我什至不知道引导是关于)。
  3. 我没有忘记关闭主机组件中的选择器标签。
  4. 我的platformBrowserDynamic().bootstrapModule(AppModule);代码中没有。
  5. 编译器不显示任何错误消息。

父母的模板是这样的:

<div id="cont">
  <div *ngFor="let n of nodes">
    <app-file-selection [jspinst]="jspl" *ngIf="n.type === 'app-file-selection'"></app-file-selection>
  </div>
</div>
  <button type="button" mat-icon-button matTooltip="Files selection" (click)="addNode('file-selection')"><mat-icon aria-label="Side nav toggle icon">insert_drive_file</mat-icon></button>

我知道这种问题被问了一遍又一遍,但我的搜索似乎没有帮助,在此先感谢。

编辑 我已经尝试将随机分配放置在构造函数中(导致两个 id 一个由 jsplumb 捕获,一个由父组件接收),并将其放置在 OnInit 中(结果只有一个 id 但父组件不知道)。

标签: angulartypescriptconstructorangular6jsplumb

解决方案


您可以使用局部变量“let i = index”来获取 *ngFor 数组的索引(在您的情况下为节点)。并使用(单击)传回,将逻辑写入您的 parent.component.ts 文件。

<div *ngFor="let n of nodes; let i = index">
  <<app-file-selection (click)="addNode(i)></<app-file-selection>
</div>

推荐阅读