What could cause a member variable to be uninitialized in the ngInit method in Ionic/Angular, even though it was initially set in the constructor

Despite setting the modal form to be bound to an instance of "Foo" during its construction, I encountered a strange issue where, post-constructor, this.foo became undefined. Even after verifying this through breakpoints and console.log, the problem persisted.

--

EDIT: Although I managed to find a workaround by moving the assignment of foo to ngOnInit() instead of within the constructor, my initial question regarding this behavior still remains.

--

Template:

<ion-header>
    <ion-toolbar>
      <ion-title>New Foo</ion-title>
    </ion-toolbar>
  </ion-header>

  <ion-content>
    <ion-list>
      <ion-item>
        <ion-input placeholder="Name" [(ngModel)]="foo.name"></ion-input>
      </ion-item>
      <!-- etc... -->
    </ion-list>

    <ion-button expand="block" color="primary" (click)="create()">
      Create
    </ion-button>
</ion-content>

Component:

export class FooModalComponent implements OnInit {

  foo: Foo = new Foo();

  constructor(
    private modalController: ModalController,
    private navParams: NavParams
  ) { 
    const inputFoo = this.navParams.get("foo");

    if (inputFoo) {
      // this shouldn't matter, as foo would have to be truthy (not undefined)
      this.foo = inputFoo;
    }

    // logs this.foo as expected
    console.log(this.foo);
  }

  ngOnInit() {
    // logs: undefined
    console.log(this.foo);
  }

  close() {
    this.modalController.dismiss();
  }

  create() {
    this.modalController.dismiss(this.foo);
  }
}

Model:

export class Foo {
    name: string;
}

Answer №1

In the latest versions of Ionic (potentially 4 and above), data that is sent to modals using componentProps or NavParams will automatically be linked to the appropriate class variables in the component being displayed. If you send an undefined variable, the related field will be effectively removed. This process occurs after the object has been constructed but before ngOnInit is triggered, which explains why your workaround was successful.

The Ionic 5 documentation suggests using @Input annotations for this purpose, however, it seems to work without them as well, even though there's no official confirmation on this claim.

Here's what you likely did:

this.modalController.create({
  component: FooModalComponent,
  componentProps: { foo: foo } // where foo could potentially be undefined
})

To prevent passing an undefined value for foo, you can try something like this:

this.modalController.create({
  component: FooModalComponent,
  componentProps: foo ? { foo } : {}
})

Alternatively, like you did, you can reassign variables in ngOnInit if necessary. As a side note, you may no longer need NavParams in the constructor since the passed parameters are already linked by this point.

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

Issue with Angular app using Azure AD not redirecting to specified path after successful login

My angular webapp is connected to Azure AD/Entra Id for user authentication. The redirect URI in my Azure AD app is set as "http://localhost:4200/translate". Here are my defined routes: const routes: Routes = [ { path: 'translate', path ...

The Angular application is currently building successfully, however when launched it displays a blank white screen. Upon checking the network tab

Seeking assistance as I am encountering a blank screen in the browser after debugging my Angular 15 application. The workspace does not exhibit any issues or errors. However, upon exploring the Network tab in DevTools, I observed that config.js, styles.css ...

Utilizing useClass in Angular's APP_INITIALIZER

Before my application starts up, I require some API data and am currently handling it with APP_INITIALIZER and useFactory. However, I aim to enhance the structure by separating all the code from app.module.ts: app.module.ts import { NgModule} from '@ ...

Show the Search Results from Angular 2 in a Separate Component

When I search, the names are displayed on a suggestion list without any issues because they are not in a separate component. Search HTML <input type="text" placeholder="Search" (keyup)="getSuggestion($event.target.value)"> <div class="suggest ...

The 'Component' binding element is assumed to have an unspecified 'any' type in TypeScript

Hello, I'm new to coding and encountering an issue with the code below. My goal is to create a protected "Dashboard" page, but I keep getting a binding error that says: Binding element 'Component' implicitly has an 'any' type.ts( ...

Communication among sub applications is crucial for the success of Micro Frontends

After researching the best practices for frontend applications, I made the decision to refactor our monolith application. Instead of choosing between micro frontends and mono repo approaches, I decided to merge them both in a unique way. I plan to create ...

Cannot trigger event ascn.onchange does not exist as a function

Need to trigger the onChange function and pass parameters within it. Here's what I have tried: setTimeout(function() { document.getElementById(input.key)?.onchange({}) }, 200); Encountering the following error message: cn.onchange is not a function ...

What is the best way to display two columns in each row using Angular?

Can you please provide guidance on how to display two columns in each row using Angular? I am attempting to showcase only two columns per row, and if there are more than four items, I want to display them on an ion-slide. Further details will be provided. ...

To close the Muix DateTimePicker, simply hit the Escape key or click anywhere outside of the picker

I'd like the DateTimePicker to only close when the user presses the action buttons, not when they click outside or press Escape. Unfortunately, I haven't found any props to control this behavior yet. <DesktopDatePicker closeOnSelect={false} s ...

What are the steps for personalizing themes in the Monaco editor?

I'm currently working on a code editor with Monaco. The syntax highlighting in Monaco for Javascript and Typescript only highlights keywords as dark blue, strings as brown, and numbers as light greenish-yellow. My goal is to customize the vs-dark the ...

What is the best way to bypass TS1192 when incorporating @types/cleave.js into my Angular application?

Using cleave.js (^1.5.2) in my Angular 6 application, along with the @types/cleave.js package (^1.4.0), I encountered a strange issue. When I run ng build to compile the application, it fails and shows the following errors: ERROR in src/app/app.component. ...

Ways to evaluate a String that is thrown using Jest

I encountered a scenario where a function throws a string. Although Jest provides the toThrow matcher for testing functions that throw errors, it only works when an Error object is thrown. Is there a way to test if a string is thrown using Jest? The giv ...

I am attempting to activate the "about us" button on the website. I have successfully included the path and added a router link to the containing div of the button. However, there seems to be something

In my app, the first step involves specifying the path in the routing module. Following that is defining the home component, then the app component, and finally creating the button using HTML. Setting up the path in the app.routing.module.ts file <div ...

Utilizing AWS Amplify with TypeScript and TypeScript Lambdas for powerful web development

Currently, I am working on a project that involves a nextjs frontend with TypeScript and AWS Amplify for the backend. My intention is to write my Lambda functions in TypeScript as well. However, I have encountered an issue where I have one tsconfig.json fi ...

Encountering a "Missing Access" error on the Discord.js API when trying to register my slash commands

Three years ago, I created a small Discord bot in Typescript that is now present on over 80 guilds. Recently, I made the decision to update it from discord.js-v12.3.1-dev to discord.js-v13.6, while also integrating the popular slash commands feature. Howe ...

Leveraging the Map function with Arrays in TypeScript

Is there a way to dynamically render JSON data into a component using array.map in Typescript? I am running into an error with the code snippet below. const PricingSection: FC<IProps> = ({ icon, title, price, user, observations, projects, intervie ...

Problems with installing ambient typings

I'm having trouble installing some ambient typings on my machine. After upgrading node, it seems like the typings are no longer being found in the dt location. Here is the error message I am encountering: ~/w/r/c/src (master ⚡☡) typings search mo ...

An issue occurred with Ionic 4: TypeError - Unable to access property 'name' as it is undefined

None of the answers to similar questions have provided a solution for me SITUATION: I've been setting up a SQL Server connection from my Ionic app. You can check out my previous question for more details The workflow goes as follows: Ionic connects ...

Deactivate additional fields when choosing an option from the drop-down selection menu

When designing a form with a select dropdown that displays various options, I encountered an issue. I want to disable certain fields if a specific option is chosen from the dropdown. For instance, if "Within Company" is selected in the transaction type, I ...

The payload from the Axios POST request is failing to reach its destination endpoint

I have two Express servers up and running - a gateway and an authentication service. I am facing an issue where the payload I set in the body of a request from my gateway to the authentication server never seems to arrive, despite there being no apparent C ...