An issue has occurred: Cannot access null property '0' | Angular version 7

Currently, I am attempting to access Observable in the component.html file using the following code:

{{ (pins | async)[0]?.state }}

I am uncertain if this approach is valid, but I am looking to access a single part of the Observable list in HTML without utilizing *ngFor loop. (I am specifically working with Firebase.) Below is the code snippet from component.ts:

pins: Observable<any[]>;

this.pins = this.db.list('pins').snapshotChanges().pipe(
  map(changes => 
    changes.map(c => ({ $key: c.payload.key, ...c.payload.val() }))
  )
);

Furthermore, here is the JSON data for 'pins':

[
  {
    "$key": "0",
    "pin": 5,
    "state": true
  },
  {
    "$key": "1",
    "pin": 4,
    "state": false
  },
  ...
]

The code functions correctly for the first item, however, it encounters an issue when trying to display subsequent items, resulting in the error message:

ERROR TypeError: Cannot read property '0' of null
    at Object.eval [as updateRenderer] (HomeComponent.html:88)
...

Your assistance in resolving this issue would be greatly appreciated. Thank you!

Answer №1

To ensure accurate retrieval of items from a list, always check the variable length before accessing its index position:

Modify your HTML as follows:

<ul *ngFor="let pin of pins; let i=index">
    <li>{{ pin.state }} <button mat-button (click)="update(i,pin)">Update Status</button></li>
</ul>
<span *ngIf="pins">
   {{ pins[0].state }} and {{pins.length}}
</span>

In your TypeScript file:

import { Component } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/database';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  pins: any;

  constructor(private db: AngularFireDatabase) { }

  ngOnInit() {
    this.db.list('pins').valueChanges().subscribe(value => {
      this.pins = value;
    });
  }
  
  update(i, pin){
    this.db.object('/pins/' + i).update({ pin: pin.pin, state: !pin.state });
  }
}

Check out this WORKING EXAMPLE for reference.

Answer №2

app.component.ts

export class AppContainer {
      data: Observable<any[]>;
      dataList = [];

      constructor(...) { }

      initialize() {
       ...
       data..subscribe(data => this.dataList = data);
      }

    }

app.component.html

{{ data[0].info }}

or try:

<ng-container *ngFor="let item of data | async; let j = index;">
 <div  *ngIf="j === 0">{{ item.info }}</div>
</ng-container>

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

Transitioning Angular from TSLint to ESLint: Addressing the Banana-In-Box Issue

Encountering major hurdles during the transition from TSLint to ESLint for my Angular project. I've set up a new project (currently in Angular 9) and then proceeded to upgrade to Angular 10.2. Following the instructions outlined in the @angular-eslint ...

Tips for pressing the enter key to submit when faced with two buttons

I am developing a form with two input fields and their respective submit buttons. I want users to be able to enter text into either field, hit the Enter key, and have it trigger the same action as clicking the submit button. Currently, pressing Enter after ...

How is it possible for the entire JavaScript file to run when all I am doing is exporting a single function

I have a function being exported: import { MongoClient } from 'mongodb'; import nextConnect from 'next-connect'; const client = new MongoClient('mongodb://localhost:27017/nextauth', { useNewUrlParser: true, useUnifiedTop ...

Discovering an item within an array of objects using the find method in Ajax

Within my backend PHP code, I iteratively define the following: foreach ( $data as $res ){ $approved[ ] = [ 'id' => $count, 'title' => "some title" ]; $count++;$title=... ) This eventually leads to the creation ...

Table displaying the frequency of words in node.js outputs

I've been working on a project to create a table in the server that displays the frequency of words found in a text file specified by the user. Here's the breakdown of what needs to be done: 1) Verify that the file is indeed a text file. 2) Open ...

There are several attributes that Selenium could not find in the element

My goal is to extract the location of an image from a website using Selenium. Below is the code I have written: WebDriver driver = new ChromeDriver(); driver.get("http://mini.imbc.com/index.html?service=onair&channel=mfm"); WebElem ...

What is the best way to allow the browser to either download a file or open it in a new tab based on what is feasible? (while maintaining the actual file

Currently in my web application, which utilizes Angular for the front-end and .Net Core for the back-end, there is a page where users can click on server-side stored files. The desired behavior is for the file to open directly in a new tab if the browser a ...

Do I still need to use @types/core-js for TypeScript typings in a Node.js application?

I manage multiple Node.js projects that focus on backend development and utilize a straightforward TypeScript setup. Prior to March 2018, my package.json file included the following: "devDependencies": { "@types/core-js": "^0.9.46", "@types/nod ...

Positioning an HTML table with the use of a for loop in JavaScript

Detail of the project: -Utilizing a javascript for loop, my program extracts data from an external javascript array titled "arrays.js" and organizes it into an HTML table. The goal is to align the appropriate data under the "Date Name Address Amount" colum ...

What is the best way to set up an on-change listener for material-ui's <CustomInput...>?

I'm currently utilizing the React dashboard created by Creative Tim. I have a question regarding how to set up an onChange listener for a Here is the code snippet for the custom input class: import React from "react"; import classNames from "classna ...

Encountering an error in Internet Explorer 11 while loading a page with Angular 2: SCRIPT5009 - 'System' is undefined

I recently created a single page application using Angular 2, node, and express. The app works perfectly on Chrome and Firefox, but I'm facing issues with Internet Explorer 11. When I tried to run the code, I encountered an error related to System wit ...

Tips for updating border color when focused with styled-components

How can I change the border color of an input on focus using styled-components and React? Here is the code snippet I am currently using: import React from "react"; import PropTypes from "prop-types"; import styled from "styled-components"; const String ...

The functionality of data binding becomes unclear when the ngif directive is applied to a mat-selection-list in

I am facing an issue with displaying a mat-selection-list based on a condition. Since adding the ngif condition, the data is consistently being set to undefined. I am struggling to identify the root cause of this problem. Thank you in advance for your assi ...

Failed Ajax request due to SyntaxError: JSON parsing error with unexpected input at position 0

I am struggling to successfully execute a call to my controller from the view using an Ajax Post method. Below is the ajax call: var Model = { Ration: "123", Batch: "2323", Ingredien ...

Adding a function to the window object using Webpack version 5

After transitioning from Webpack 4 to Webpack 5, I encountered an issue with attaching functions to the window object in my index.js file. Previously, I had a function defined on the window object like so: index.js window.someFunction = function (...argum ...

Learning the process of reading a JSON file from a folder in an ASP.NET project

In the Script folder, I created a subfolder called "js" where I stored a file named json containing an array of cities. I attempted to read this file from the folder and return a list to display in my select view. { "city": [ { "Name": "Chicago" }, ...

Is it okay if I use the attached code to create a filter table?

Click here to view the attached code I have included a photograph containing the lengthy code in this message for your reference. Could you please take a look and assist me with creating a filter table using that code? ...

Tips for utilizing [ngClass] with various class situations in Angular4

My current div structure is as follows: <div class="class-a" [ngClass]="{'class-b': !person.something}"> However, I now need to add an additional condition... I want the div to have class-a if one condition is met, class-b if another con ...

Adding a namespace in a .js file

In the MVC application I'm developing, all JavaScript for the pages is stored in separate JavaScript files without any script tags on the pages. There's a Messages class containing Errors, Information, and Confirmation classes with static strings ...

What causes the non-reachable part of the ternary operator to be evaluated prior to updating the state with setTimeout?

Check out my latest code snippet for a react component that renders a massive component. While the huge component is still rendering, a loading indicator will be displayed. import * as React from "react"; import ReactDOM from "react-dom"; import {HUGECom ...