emvidi
emvidi

Reputation: 1310

angular 2 template use console.log

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

Upvotes: 67

Views: 78888

Answers (4)

Tsvetoslav Tsvetkov
Tsvetoslav Tsvetkov

Reputation: 1176

Here is a simple and working solution, if you want to print each item in the console, without creating any additional method in the .ts file

  1. Add in .ts file console
export class AppComponent  {
    console = console;
}
  1. Add in .html file console.log
<li *ngFor="let item of items">
    {{ console.log('-', item) }} 
    <p>{{item.name}}</p>
</li>

Upvotes: 3

Flavio Occhipinti
Flavio Occhipinti

Reputation: 127

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

Upvotes: 12

Vivek Doshi
Vivek Doshi

Reputation: 58593

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

Upvotes: 45

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658017

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

Upvotes: 136

Related Questions