简体   繁体   中英

Angular component multiple instance binding input problem

I am using an Angular Wrapper for JSON Editor like this:

<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>

The problem is that eventParams should be different for each editor but it is not varying.

I think problem is this component code (but not sure) (This line is in the component taken from github):

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

The component is behaving like a singleton. Any help?

Edit: I edited this repo and added jsonchange event. Details here

You may want to use @ViewChildren with a direct reference to the component instead of a template variable string, to get all the JSON editors references:

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

// ...

jsonEditorContainers.find(...);

It returns a QueryList that allows you to iterate through all ElementRef , and monitor the changes with an Observable changes .

What is eventParams ? What is jsonChange ? I could be wrong, but data doesn't seem to be two way bindable either, according to the source code.

It seems like you might be looking for something like this:

<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>

You can then read the test_step_id in your changeStepActions method. If this works, I don't know how you made it compile in the first place.. are you using a CUSTOM_ELEMENTS_SCHEMA ?

Its not necessary to use @ViewChildren for that you have to rewrite the entire code of component, make sure while using @ViewChild you pass correct editor reference.

As following

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

Stackblitz example for refernce :

Click here for code example

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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