Vamsi Krishna
Vamsi Krishna

Reputation: 79

How do I use an if statement in Angular?

I am want to use an if statement to only console.log is there is a "todo.title". But when I write out the if statement a red line appears below the if statement.

Ok, let me explain this problem with a bit more detail. This is what the webpage looks like: enter image description here

All the initial todo items are coming from http://jsonplaceholder.typicode.com/todos. And I added a new line called "test" via the input box. When I clicked on the check box for "delectus aut autem", it showed the proper console.log. But I when I clicked on the checkbox for "Test", it showed that error message in the console.

I am trying to change the code so that it will only console for the items that came from the jsonplaceholder website and I am trying to do that by saying "only if there is a todo.title, then console.log, but if not do not console.log anything. Here is my new code:

onToggle(todo) {
  // Toggle in UI
  todo.completed = !todo.completed;
  // Toggle on server
  this.todoService.toggleCompleted(todo).subscribe(    
    todo => { 
      if (todo.title) {
        console.log(todo);
      }        
    }); 
}

Upvotes: 0

Views: 290

Answers (2)

dmoore1181
dmoore1181

Reputation: 2102

I think that you may be needing something on the lines of the following, as your if statement would always be true if you compare the same two objects.

onToggle(todo){
    //Toggle in UI
    todo.completed = !todo.completed;
    //Toggle on server
    this.todoService.toggleCompleted(todo).subscribe( ()=>
       if(todo.title){
           console.log(todo.title);
       }
    );  
}

Upvotes: 1

Sunny
Sunny

Reputation: 4809

It should be .subscribe( () => { <your code (if...)> } );

Upvotes: 4

Related Questions