mohsen1 / json-formatter

Angular directive for collapsible JSON in HTML
http://azimi.me/json-formatter/demo/demo.html
Other
372 stars 85 forks source link

Are you planning to create an Angular 2 component with similar functionality? #62

Open carttrac opened 7 years ago

mohsen1 commented 7 years ago

For Angular 2 create a simple component in your codebase that uses JSON Formatter JS.

mhalttu commented 7 years ago

Could somebody post an example of such a component here?

jwhitmarsh commented 7 years ago

@mhalttu loosely something like:

import { Component, OnChanges, Input, ElementRef, ViewChild, Renderer } from '@angular/core';
import { isObject } from 'rxjs/util/isObject';
import { isArray } from 'rxjs/util/isArray';
import JSONFormatter from 'json-formatter-js';

@Component({
  selector: 'json-viewer',
  template: `<div #jsonViewer></div>`,
  styleUrls: ['./json-viewer.component.sass']
})
export class JsonViewerComponent implements OnChanges {
  @ViewChild(`jsonViewer`) input: ElementRef;

  @Input() json: Array<any> | Object | any;

  constructor() { }

  ngOnChanges() {
    // Do nothing without data
    if (!isObject(this.json) && !isArray(this.json)) {
      return;
    }

    const formatter = new JSONFormatter(this.json);
    this.input.nativeElement.appendChild(formatter.render());
  }
}
alexzuza commented 7 years ago

Here is an example for angular2 https://plnkr.co/edit/6Cbs6pIPqGlXM0hmXF9n?p=preview. If Mohsen Azimi doesn't mind i can make it as library

IAMtheIAM commented 6 years ago

@alexzuza Very AWESOME! Thank you. While I was able to get it to work in Angular 2 using basic document.body.appendChild() this is not the proper way for an angular app. Using you plunker, I copied the code and it works PERFECTLY.

Maybe you can release this as an NPM package for easy consumption. Very good work to @mohsen1 for creating the original code as well!!! It was hard to find a library that could take plain JSON and convert it into a tree view with expand/collapse - they all wanted custom name properties which means they don't work with plain JSON.

Thanks guys.

IAMtheIAM commented 6 years ago

@jwhitmarsh Great minimal example - except I had to use ngAfterViewInit{} lifecycle hook to get it to render instead of ngOnChanges - what is ngOngChanges going to do the way you suggested it?