Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Angular Material Dialog & JSON.stringify

I am unable to show the string provided by JSON.stringify including the spaces for indentation inside a material dialog of my Angular project. It always appears as a raw data string, without any spacing for the indentation, even if I use the spaces parameter.
The funny thing is that the same code provides a good indentation if I console.log it.

component.ts :

[...]
onClickJSON() {
    let dialogConfig = new MatDialogConfig()
    dialogConfig.data = {
        json: this.item
    }
this.jsonDialog.open(JsonDialogComponent, dialogConfig)
[...]

dialog.ts :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[...]
export class JsonDialogComponent implements OnInit {

    json: string;

    constructor(private dialogRef: MatDialogRef<JsonDialogComponent>,
                @Inject(MAT_DIALOG_DATA) public data: any) {
    console.log(JSON.stringify(this.data['json'], null, 4)) //Good appearance
    this.json = JSON.stringify(this.data['json'], null, 4) //Bad appearance, like raw data
[...]

dialog.html :

<p>
    {{json}}
</p>

>Solution :

That’s because you didn’t use the correct tag.

Instead of using <p>, use either

<pre>{{ json }}</pre>

or

<pre><code>{{ json }}<code></pre>

More in depth, this is due to CSS styling, you can check the native styling of the pre tag and apply it to your p if you want. But semantically speaking, it’s better to use <pre> than <p> in that case.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading