Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does *ngIF always evaluate to true in my Angular app?

I define Todo as follows:

export class Todo {
  id: number;
  title: string;
  complete: boolean = false;
  editMode: boolean = false;
  }

I have the following data service:

  getAllTodos(): Observable<Array<Todo>> {
     return this.aHttpService.get<Array<Todo>>('http://localhost:3000/todos');
  }

Then, I have this component:

import { Component, OnInit } from '@angular/core';
import { TodoDataService } from '../todo-data.service';
import { Todo } from '../todo';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'app-all-tasks',
  templateUrl: './all-tasks.component.html',
  styleUrls: ['./all-tasks.component.css']
})
export class AllTasksComponent implements OnInit {
  constructor(private todoDataService: TodoDataService) {}
  allTodos: Observable<Array<Todo>>;

  ngOnInit() {
    this.allTodos = this.todoDataService.getAllTodos();
  }
}

and in the template I have:

<li *ngFor="let todo of allTodos | async" >
  <span *ngIf="todo.complete; else elseBlock"><span>&#10003;</span></span>
  <ng-template #elseBlock>
    <span>&#x2715;</span>
  </ng-template>
  <span>{{todo.title}}</span>
</li>

However todo.complete always evaluates to true, despite the fact that the incoming data isn't always true. (I validate that via a call to the service with Postman...)

Why is the value always true?

I should note that the todo.title renders correctly.

Update

A call to http://localhost:3000/todos via Postman returns:

[
{
    "id": 1,
    "title": "Learn TypeScript",
    "complete": "true",
    "editMode": "false"
},
{
    "id": 2,
    "title": "Learn Angular changed",
    "complete": "true",
    "editMode": "false"
},
{
    "id": 3,
    "title": "Learn to Read",
    "complete": "true",
    "editMode": "false"
},
{
    "id": 4,
    "title": "Learn to Write",
    "complete": "false",
    "editMode": "false"
},
{
    "title": "Learn how to type",
    "complete": "true",
    "editMode": "false",
    "id": 5
},
{
    "title": "Learn how to drive",
    "complete": "false",
    "editMode": "false",
    "id": 6
}
]
like image 840
Nick Hodges Avatar asked Mar 05 '23 06:03

Nick Hodges


1 Answers

I was sure complete was coming as a string instead of a boolean.

Since a string in *ngIf(and generally in a JavaScript if(...)) always resolves to true(as long as it's not empty('')), the *ngIf block was always getting displayed on the screen and elseBlock was not.

Use this to fix it:

<span *ngIf="todo.complete === 'true'; else elseBlock"><span>&#10003;</span></span>
like image 111
SiddAjmera Avatar answered Mar 15 '23 23:03

SiddAjmera