angular - 组件的构造函数调用了两次
问题描述
所以我有这个子组件,其中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
事件触发时检索相关节点。我发现了一些类似的问题,但没有一个帮助:
- 我的按钮
type="button"
上有一个 - 我没有引导父组件和子组件,实际上我没有引导它们中的任何一个,我已经检查过
app.module.ts
(我什至不知道引导是关于)。 - 我没有忘记关闭主机组件中的选择器标签。
- 我的
platformBrowserDynamic().bootstrapModule(AppModule);
代码中没有。 - 编译器不显示任何错误消息。
父母的模板是这样的:
<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 但父组件不知道)。
解决方案
您可以使用局部变量“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>
推荐阅读
- python - 如何使用 cogs 实现更改前缀命令?
- css - box-shadow 被父元素截断
- java - ConcurrentHashMap 无法按预期工作
- json - 我收到一个 Swift Decoding 错误:解析 JSON,找到一个期望字典的数组?
- node.js - 使用服务器到服务器通信的另一台服务器上的 Nodejs 子进程
- javascript - 即使我没有错误,我的模拟时钟也无法处理 java 脚本
- c# - 在包含 Picker 的自定义控件中绑定 ItemSource 属性
- javascript - Uncaught (in promise) SyntaxError: Unexpected end of JSON input when fetch get data
- c - 在不同的头文件中使用同名的宏
- google-calendar-api - Google Calendar API:当会议在其日历中不存在时,用户作为与会者存在