angular 2 template use console.log

Angular

Angular Problem Overview


I would like to use the console.log inside the inline template but can't find any directions.

@Component({
  selector:"main",
  providers: [ItemService],
  template:`
    <ul>
     <li *ngFor="let item of items">
      {{console.log(item)}} <----- ??? 
      <p>{{item.name}}</p>
     </li>
    </ul>

  `
})
export class HomeComponent {
  private items: Array<ItemModel>;

  constructor() {}
}

Angular Solutions


Solution 1 - Angular

You can't access globals, statics, ...

You can only access properties of the component the view belongs to.

You can add a

log(val) { console.log(val); }

to your component and use it like

{{log(item)}} 

but be prepared this to be logged quite often (every time change detection runs).

For debugging I prefer

 {{item | json}} 

Solution 2 - Angular

> Better way to do it : > > This way you can access all the console properties on template side


> Component side :

export class AppComponent  {
  console = console;
}

> Template Side :

{{ console.log('----------------> Logging') }}
{{ console.warn('----------------> Warning') }}
{{ console.error('----------------> error') }}

WORKING DEMO

Solution 3 - Angular

an easy way to debug is to create a pipe for that :

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'log'
})
export class LogPipe implements PipeTransform {
    transform(value: any, args?: any): any {
        console.log(value);
        return null;
    }
}

Then you just have to write this in the template :

{{ variable | log }}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionemvidiView Question on Stackoverflow
Solution 1 - AngularGünter ZöchbauerView Answer on Stackoverflow
Solution 2 - AngularVivek DoshiView Answer on Stackoverflow
Solution 3 - AngularFlavio OcchipintiView Answer on Stackoverflow