Adi Goldner
Adi Goldner

Reputation: 9

angular2 *ngIf doesnt work when true and array is empty

so I have this code :

this is the templateUrl:

<button class="btn btn-success" (click)="showNewPop()" >New</button>{{shownew}}
<app-new-pop *ngIf="shownew"  (close)="closeNewPop($event)"></app-new-pop>

and this is the Component.ts

 private shownew = false;
 private myBooksArr:Book[];

 constructor(private bookService:BookService) { 
   this.myBooksArr = Array<Book>();
 }

 ngOnInit() {
   this.getBooks();  
 }

 showNewPop(){
   this.shownew = true;
 }

 closeNewPop(newBook:Book){
   this.shownew = false;
   if (newBook) {
     this.myBooksArr.splice(0, 0, newBook);
   }
 }

 private getBooks(){
   this.bookService.getBooks().subscribe(data=>{
     data.items.forEach(element => {
       this.myBooksArr.push(new Book(element.id,
                                     element.volumeInfo.authors,
                                     element.volumeInfo.publishedDate,
                                     element.volumeInfo.title));
     });
   });
 }

now the problem is that when ever the myBooksArr array is empty shownew becomes true but the *ngIf does not show the app-new-pop Component

and i can't figure out why

this is the delete book function if it helps

 showDeletePop(i:number) {
   this.currnetBook = this.myBooksArr[i];
   this.currnetBook.indedx = i;
   this.showDelete = true;
 }

 closeDeleetePop(mydelete:boolean){
   this.showDelete = false;
   if(mydelete){
     this.myBooksArr.splice(this.currnetBook.indedx,1);
   }
 }

Update!!

found a hack that works if any one is interested. this is it :

 private flag:boolean= false;
 showNewPop(){
   console.log(this.myBooksArr.length);
   if(this.myBooksArr.length==0){
     this.myBooksArr.push(new Book("",[""],"0",""))
     this.flag =true;
   }
   this.shownew = true;
 }

 closeNewPop(newBook:Book){
   this.shownew = false;
   if(newBook && !this.flag){
     this.myBooksArr.splice(0, 0, newBook);
   }
   if(newBook && this.flag){
     this.myBooksArr.splice(0,1,newBook);
     this.flag = false;
   }
 }

I still would like to know why didn't it work in the first place tho
if you know it would be cool

Upvotes: 0

Views: 79

Answers (2)

nicolas.leblanc
nicolas.leblanc

Reputation: 630

Aren't you mising a } before ngOnInit ?

constructor(private bookService:BookService) { 
  this.myBooksArr = Array<Book>();
}
ngOnInit() {
  this.getBooks();  
}

Upvotes: 0

Logan_B
Logan_B

Reputation: 527

Try putting the *ngIf in a div.

<div *ngIf="shownew">
<app-new-pop (close)="closeNewPop($event)"></app-new-pop>
</div>

In the reference to ngIf: https://angular.io/api/common/NgIf

@Component({
  selector: 'ng-if-simple',
  template: `
    <button (click)="show = !show">{{show ? 'hide' : 'show'}}</button>
    show = {{show}}
    <br>
    <div *ngIf="show">Text to show</div>
`
})
class NgIfSimple {
  show: boolean = true;
}

Upvotes: 1

Related Questions