Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON pipe in Angular 2 is not working

When I try to pipe my data by JSON pipe I get the following error in the console:

Unhandled Promise rejection: Template parse errors:
The pipe 'json' could not be found (...

What am I doing wrong?

like image 569
Paweł Szymański Avatar asked Nov 02 '16 20:11

Paweł Szymański


People also ask

Can we use JSON in pipe?

JsonPipe uses json keyword to convert value into JSON string using pipe operator as follows. For the example find the object of Address class in our component. address1 = new Address('Dhananjaypur', 'Varanasi', 'India'); Use json keyword with pipe operator (|) to convert the given object into JSON string.

What is the use of JSON pipe in Angular?

Angular Json Pipe converts a value or object into JSON formatted string. Usually we will get the data from the server in JSON format, and we will bind it to HTML. To know the exact JSON data coming from the server we can use network tab in browser developer tools.

Which pipe is used for pretty printing the JSON value?

Angular json pipe is also useful for debugging purpose because it displays all the properties of the object in pretty print json format.

How angular pipes work?

You use data binding with a pipe to display values and respond to user actions. If the data is a primitive input value, such as String or Number , or an object reference as input, such as Date or Array , Angular executes the pipe whenever it detects a change for the input value or reference.


3 Answers

Most likely you forgot about importing CommonModule:

import { CommonModule } from '@angular/common';


@NgModule({
    ...
    imports: [ CommonModule ]
    ...
})

As noted in the comments, do this in the module where you're using the json pipe.

like image 54
Paweł Szymański Avatar answered Oct 24 '22 19:10

Paweł Szymański


In my case CommonModule was added, but the component was not part of declaration of any module

(I was creating component dynamically by using ContainerRef)

like image 43
Reza Avatar answered Oct 24 '22 18:10

Reza


Your parent Module of the component should be like this.

import {NgModule} from '@angular/core';
import {AuditTrailFilterComponent} from './components/audit-trail-filter/audit-trail-filter.component';

import {CommonModule} from '@angular/common'; <-- This is important !!!!

@NgModule({
  imports: [
    CommonModule, <-- This is important !!!!
  ],
  declarations: [AuditTrailFilterComponent],
  exports: [
    AuditTrailFilterComponent
  ]
})
export class AuditTrailModule {
}
like image 44
Semir Hodzic Avatar answered Oct 24 '22 18:10

Semir Hodzic