繁体   English   中英

Angular 组件多实例绑定输入问题

[英]Angular component multiple instance binding input problem

我正在为JSON 编辑器使用Angular Wrapper ,如下所示:

<div *ngFor="let act of editedActions" class="w-100-p p-24">
  {{act.test_step_id}}
  <json-editor [options]="editorOptions" [(data)]="act.action_json" [(eventParams)]="act.test_step_id" (jsonChange)="changeStepActions($event)"></json-editor>
  <button mat-raised-button class="w-100-p mt-24" color="primary" (click)="editRecordJson(act.test_step_id)">
    <span>Update</span>
  </button>
</div>

问题是每个编辑器的eventParams应该不同,但它并没有变化。

我认为问题是这个组件代码(但不确定)(这一行在从 github 获取的组件中):

@ViewChild('jsonEditorContainer', { static: true }) jsonEditorContainer: ElementRef;

该组件的行为就像一个单例。 有什么帮助吗?

编辑:我编辑了这个 repo 并添加了 jsonchange 事件。 详情在这里

您可能希望使用@ViewChildren直接引用组件而不是模板变量字符串,以获取所有 JSON 编辑器引用:

@ViewChildren(JsonEditorComponent) jsonEditorContainers: QueryList<ElementRef>;

// ...

jsonEditorContainers.find(...);

它返回一个QueryList ,允许您遍历所有ElementRef ,并使用 Observable changes监视changes

什么是eventParams 什么是jsonChange 我可能是错的,但根据源代码,数据似乎也不是双向可绑定的。

看起来你可能正在寻找这样的东西:

<div *ngFor="let act of editedActions" class="w-100-p p-24">
  <json-editor [options]="editorOptions" 
               [data]="act.action_json"
               (change)="changeStepActions($event, act.test_step_id)">
  </json-editor>
</div>

然后,您可以阅读test_step_idchangeStepActions方法。 如果这有效,我不知道你是如何编译它的。你在使用CUSTOM_ELEMENTS_SCHEMA吗?

没有必要使用@ViewChildren,因为您必须重写组件的整个代码,确保在使用@ViewChild 时传递正确的编辑器引用。

如下

@ViewChild('carEditor' ) carEditor: JsonEditorComponent;
@ViewChild('mobileEditor') mobileEditor: JsonEditorComponent;

Stackblitz 示例供参考:

单击此处查看代码示例

To use multiple jsoneditors in your view you cannot use the same editor options.

You should have something like:

<div *ngFor="let prd of data.products" class="w-100-p p-24" >
  <json-editor [options]="makeOptions()" [data]="prd" (change)="showJson($event)"></json-editor>
</div>
makeOptions = () => {
  return new JsonEditorOptions();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM