angular2 *ngIf fails to render content when condition is true and array is empty

Here's the code I'm working with:

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 here is the Component.ts file:

 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, I'm facing an issue where when the myBooksArr array is empty, shownew becomes true but the *ngIf does not display the app-new-pop Component.

I can't seem to figure out why this is happening.

Below is the delete book function for reference:

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

I found a workaround that works, in case anyone is interested. Here's the solution:

 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 am still curious to know why it didn't work initially though. If you have any insights, please share!

Answer №1

Consider placing the *ngIf directive inside a div element.

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

Learn more about ngIf at this link: 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;
}

Answer №2

Could it be possible that you forgot to include a closing bracket } before the ngOnInit method?

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the magic of Angular and RxJs: Converting JSON to an Array of Objects

I am attempting to convert a JSON HTTP request response into an array of objects (User) using RxJs: The structure of my JSON data is as follows: {"@context":"\/cotabe\/api\/contexts\/User","@id":"&bso ...

The post method is functioning properly in browsers such as Firefox, Internet Explorer, and Chrome; however, it is not working in the Edge browser

I am encountering an issue with a post method in the Edge browser. Even though I am able to receive responses for the same request in other browsers like Internet Explorer, Chrome, and Firefox, Edge seems to be not responding at all. Despite conducting a s ...

Top tips for creating effective Angular 2 components

My application features a user object that stores and updates all user information using an observable provided by the userService. I am now contemplating the best practice for utilizing this user observable with components. One specific scenario involves ...

ReactJS Redux Provider fails to accept the store

I'm currently in the process of migrating my redux store from using "createStore" to "configureStore" due to the deprecation of "createStore". I am working with ReactJS 17 and TypeScript, with the following versions of Redux / Redux dependencies: &quo ...

Can someone please explain the purpose of x.ngfactory.ts files and provide tips on how to troubleshoot them when working with @angular/cli version 1.1.1

I am currently utilizing Angular 4.x, Webpack 2.x, and TypeScript 2.x. For the project build, I am using @angular/cli. When running ng serve, all code gets transpiled successfully and functions well in the view. The log output is displayed below: webpa ...

Setting up ESLint for TypeScript to enforce the "no-unused-vars" rule

In all my TypeScript projects, I utilize ESLint with specific settings in place: "extends": ["airbnb", "prettier", 'plugin:vue/recommended'], "plugins": ["prettier"], "parserOptions&quo ...

Guide on setting up global typing for AngularJS in your project

I have been working on a project that initially used the deprecated typings method for incorporating Typescript definitions. I now want to transition to using the @types method instead. Currently, we have a typings.json file located in the root of the pro ...

Type 'Partial' cannot be assigned a value when combining interfaces with generic types

Consider the following scenario: class Table<ValuesType extends DefaultTableValues = DefaultTableValues>{ public values: ValuesType; constructor(initialValues:ValuesType) { this.values=initialValues; } public set(newValues:Pa ...

Two lines in ChartJS with distinct fill gradients for each

I am facing an issue with ChartJS version 2.6 in my Ionic 3/Angular 4 app. I have set up a line chart config with 2 datasets, but I am struggling to apply individual fill gradients to each line. What I am aiming for is something like this: https://i.stac ...

Typescript: Understanding the Optional Operator and Dealing with Null Ambiguity

Seeking guidance on writing clean code, particularly regarding a property with a backing field: get value(): string { return this._value; } set value(v: string) { this._value = v; } private _value?: string; It has come to my attention that this code is co ...

Creating a distinct input for each row in a table using Angular 2

I am encountering an issue with inputs being created for each row in my PrimeNG/datatable. The problem arises from the local variable #itsmIncident, which causes confusion when trying to pass values to the "Save" button as there are multiple rows involve ...

Can callback argument types be contingent on certain conditions? For example, could argument 0 be null if argument 1 is a string?

I am attempting to implement conditional type logic for the parameter types of a callback function. In this scenario, the first argument represents the value while the second argument could be an error message. type CallbackWithoutError = (value: string, ...

What is the method for installing TypeScript declarations for packages with scopes or namespaces using @types?

My current challenge involves the use of TypeScript and my desire to utilize a scoped package such as @foo/bar or @babel/core that does not include its own type declarations. My attempted solution so far has been to execute the following command: npm ins ...

Angular is giving me a hard time setting my background image

I'm having trouble getting the background image to load on my page. No matter what I try, it just won't show up. Here's the code snippet for my page: <div class="container" [ngStyle]="{'background-image': getUrl()}"> < ...

Angular Interceptor failing to assign headers in HTTP requests

Although I am successfully setting the authToken value from my login component with a valid token (verified using Postman), the issue arises when no Authorization parameter is being added to my request header. entryComponents: [ ConfirmDialogTarget ...

React Redux not properly handling text input updates when onChange event is triggered

I have come across similar inquiries, but they haven't provided the solution I need. Currently, I am working on a React project where I am integrating redux. This is how my index.js looks: import React from "react"; import ReactDOM from "react-dom"; ...

Targeting multiple browsers in an Angular 11 project with scss: A comprehensive guide

for instance: i'm currently animating the ::placeholder pseudo element when ::focus is active input::placeholder{ color: grey; transition: all 400ms ease; position: absolute; top: 35%; font-size: 15px; } inpu ...

The error message "Angular formGroup requires a FormGroup instance. Kindly provide one."

I used angular reactiveforms to create a form. The default data is successfully printed on the form, however, I am facing an error in the console that says "formGroup expects a FormGroup instance. Please pass one in." Can someone guide me on how to resolve ...

Using conditional CSS values in Angular 8

I am currently working on a parent component and child component setup, where I am utilizing the child component's selector to display it within the parent component. Here is my child component's HTML: <div class="main-container" [n ...

When attempting to run npm install for @types/jquery, an error is returned stating "Invalid name: @types/jquery"

npm install @types/jquery npm ERR! Windows_NT 10.0.10586 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-c ...