Unable to access value of 'xxx' as it is undefined

My experience with Ionic 2 involves a component that consists of two smaller components, and data sharing is done through emitters. However, upon running the program, I encounter this particular error:

Runtime Error Uncaught (in promise): TypeError: Cannot read property 'BillNo' of undefined TypeError: Cannot read property 'BillNo' of undefined at Object.eval [as updateDirectives]

Let me share my code for better understanding:

bill-settlement.html

...
<page-bill-list (BillSelected)="onBillSelected($event)"></page-bill-list>
...
<page-bill-details [billItem]="billItem"></page-bill-details>
...

bill-settlement.ts

@Component({
  selector: 'page-bill-settlement',
  templateUrl: 'bill-settlement.html',
})
export class BillSettlement {
  ...
  billItem: BillDetail
  ...
  onBillSelected(billData: BillDetail) {
    this.billItem = billData
  }
}

bill-list.html

<ion-buttons>
  <button ion-button *ngFor="let item of billItems" (click)="getBillDetails(item)">
      {{item.BillNo}}
  </button>
</ion-buttons>

bill-list.ts

@Component({
  selector: 'page-bill-list',
  templateUrl: 'bill-list.html',
})
export class BillList {
  billItems: BillDetail[] = []
  billItem = new BillDetail()
  @Output() BillSelected = new EventEmitter<BillDetail>()
  constructor(public navCtrl: NavController,
    public navParams: NavParams,
    public billSrv: BillerService,
    public authSrv: AuthService,
    public genSrv: GenericService) {
    this.billSrv.getBills()
      .subscribe(data => {
        this.billItems = data
      })
  }
  getBillDetails(item: BillDetail) {
    this.BillSelected.emit(this.billItem)
  }
}

bill-details.ts

@Component({
  selector: 'page-bill-details',
  templateUrl: 'bill-details.html',
})
export class BillDetails {
    ...
    @Input() billItem: BillDetail
    ...
}

bill-details.html

...
<ion-input text-right type="text" [value]="billItem.BillNo" readonly></ion-input> //billItem model has BillNo property
...

The main issue lies in the fact that initially, billItem.BillNo in bill-details.ts is undefined. It only gets defined when clicking the bill number button in bill-list.html. How can I set an initial value for billItem and then replace it upon button click?

Answer №1

Make sure to load the view before setting billItem.

If you are unsure if billItem will be set, consider using a safe navigation operator like ?.

<ion-input text-right type="text" [value]="billItem?.BillNo" readonly></ion-input> //billItem model has BillNo property

An alternative is to initialize it as an empty object in the constructor of bill-details.ts:

constructor(...){
  if(! this.billItem){
    this.billItem={}
  }
}

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

The code inside the promise .then block is executing long before the promise has completed its

After spending quite some time working on this messy code, I finally have a functioning solution: loadAvailabilities() { let promises = []; let promises2 = []; let indexi = 0; //return new Promise((resolve, reject) => { this.appo ...

Reset the input or range value of an ion element whenever it appears on the screen

Whenever the user presses a button on the page, I want my ion-input and ion-range slider to reset their value to the value set by [(ngModel)] when they are loaded on the page. The slider/input fields become visible when the button is pressed. Users have th ...

Using Typescript with Vue.js: Defining string array type for @Prop

How can I properly set the type attribute of the @Prop decorator to be Array<string>? Is it feasible? I can only seem to set it as Array without including string as shown below: <script lang="ts"> import { Component, Prop, Vue } from ...

Encountering a problem when parsing a JSON file in Angular 2

When attempting to access the config.json file in my Angular2 service, I have encountered an issue. load() { return new Promise((resolve, reject) => { this.http.get('./config.json') .map(res => res.json()) ...

Promise rejection not caught: ; Zone: angular ; Task:

While using meteor and trying to set up a (click) attribute, I encountered the following error message. https://i.sstatic.net/Qzk9T.png This is my code: import { Component, NgZone, AfterContentInit } from 'angular2/core'; import { NgIf, NgFor ...

Unable to display surface chart using Plotly in Angular 12

I've been attempting to display a 3D model using Plotly (https://github.com/plotly/angular-plotly.js/blob/master/README.md), but unfortunately, the chart is not appearing. component.component.ts import { Component } from '@angular/core'; @ ...

Incorporating modules through System.JS

I integrated angular2-google-maps into my Angular 2 application for utilizing Google Maps functionality. Here is a snippet from my package.json: { "name": "angular2-quickstart", "version": "1.0.0", "scripts": { "start": "tsc && concurre ...

Exploring Object Literal Lookups in Typescript

Check out this minimal reproducible example of the issue I've created an object literal: const map = (filter: Filter) => { return { [Filter.USERS]: { fetch: async () => getUsers(), set: setUsers, }, [Filter.FIRMS]: { ...

Leverage third-party extensions instead of ionic-native plugins in your Ionic 2

Currently, I am utilizing a Cordova plugin from GitHub that is not accessible in Ionic Native. However, I have encountered an issue. How can I effectively use non-Ionic-Native plugins in Ionic 2? I attempted the following: declare var myPlugin: any; my ...

Transmitting a cookie across domains using an HTTP get request in Angular 2

Is there a way to send a cookie with Angular 2 across domains? const headers = new Headers({ 'Cookie': 'test=me'}); let options = new RequestOptions({ headers }); return this.http.get(this.specialUrl, options ) .map( (res: ...

What would be the best dimension for an Angular 11 module?

Picture yourself developing a brand new modular app in Angular and facing the decision of when to create a new module. Is it considered best practice to create a module per page if the pages do not have common components? Is there an optimal size for Ang ...

In the realm of JavaScript, the localeCompare() string method is more than willing to accept the presence of 'undefined' as a valid parameter for 'locale', while opting to outright reject any instance of

I have discovered a method to sort strings naturally const rows = ['37-SK', '4-ML', '41-NP', '2-YZ', '21', '26-BF']; console.log(rows.sort((a, b) => a.localeCompare(b, undefined, { numeric: tru ...

Using mat-form-field with the outline appearance seems to be causing some issues

When I change the body direction to RTL, the mat-form-field with appearance"outline" seems to have some issues. If you go to the https://material.angular.io site and navigate to the Form field examples, under the Form field appearance variants section, yo ...

Issue: UNSUPPORTED: The keyword "id" is not supported, please use "$id" for the schema ID after upgrading to Angular13

After upgrading from Angular 12 to Angular 13, I encountered an error while running my e2e tests. How can I go about identifying the root cause of this issue? I am able to compile with 'ng build'. /opt/wdio/node_modules/@angular-devkit/core/nod ...

What is the issue when using TypeScript if my class contains private properties while the object I provide contains public properties?

I am currently facing an issue while attempting to create a typescript class with private properties that are initialized in the constructor using an object. Unfortunately, I keep encountering an error message stating: "error TS2345: Argument of type &apos ...

Adjusting column width in Bootstrap grid when content is missing

Currently, I am encountering a problem with the grid system while attempting to create a kanban style drag and drop system. The issue is illustrated in the image below. Each card should be positioned according to the arrows shown. As the 2nd column is cur ...

Switching the keyboard language on the client side of programming languages

I'm interested in altering the keyboard language when an input element changes. Is it possible to modify the keyboard language using client-side programming languages? And specifically, can JavaScript be used to change the keyboard language? ...

Combining 2 Observables in nestjs Interceptor: A Step-by-Step Guide

I am currently working on a NestJS interceptor to geolocate an address that is being sent through a REST API. Here is the code snippet: export class PointsInterceptor implements NestInterceptor { intercept(context: ExecutionContext, next: CallHandler): O ...

Struggling to run my Pact tests using Karma and Angular

I'm struggling to run pact tests with Karma in my Angular app setup. Below is the relevant snippet from my package.json. "@angular/core": "~13.3.6", "@pact-foundation/karma-pact": "^3.1.0", "@pact-foundatio ...

What is the best way to obtain real-time data from a database in Angular without the need to constantly refresh the page

I'm currently working on a project using Angular, with my database in MongoDB and backend in Flask. I have a collection where the data is constantly changing every 10 seconds. I am developing REST APIs to facilitate sharing data between Angular and Mo ...