Angular 7 throwing errors of undefined variables

I encountered an error message that says

Property 'country' does not exist on type 'ViewComponent'. Did you mean 'country$'?

I'm at a loss on how to resolve this issue. I understand that there is an undefined variable called country, but I'm unsure where and how to set this variable. Below is the code snippet from my view.component.ts file:


import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { Country } from '../models/country';
import { CountryService } from '../services/country.service';
import { ActivatedRoute, Router, ParamMap } from '@angular/router';
import { switchMap } from 'rxjs/operators';

@Component({
  selector: 'app-view',
  templateUrl: './view.component.html',
  styleUrls: ['./view.component.css']
})
export class ViewComponent implements OnInit {

  country$:Observable<Country>;
  constructor(
        private route:ActivatedRoute,
        private router:Router,
        private countryService:CountryService) { }

  ngOnInit() {

    this.country$ = this.route.paramMap.pipe(
        switchMap((params: ParamMap)=>
            this.countryService.getCountryById(Number.parseInt(params.get('countryID')))
            ));
  }
  
  editCountry(country:Country):void{
    this.country$.subscribe(country =>{
        console.log('edit clicked');
        this.router.navigate(['countries/edit/'+country.countryID]);
        });
  }

}

Additionally, below is the code snippet from my view.component.html file:


  <label for="" class="col-sm-2 col-form-label">Name</label>
  <div class="col-sm-10">
    <label for="" class="col-sm-12 col-form-label">{{(country$ | async).countryName}}</label>
  </div>
  <div class="form-group row">
    <label for="" class="col-sm-2 col-form-label">&nbsp;</label>
    <div class="col-sm-10">
        <button type="button" class="btn btn-success fa fa-pencil-square-o"  (click)='editCountry(country)' >&nbsp;Edit</button>&nbsp;
        
    </div>
  </div>

Answer №1

The variable country is being passed to the function editCountry in your view, but it does not actually exist. In addition, you can remove it as the country$ observable is already being used within the editCountry function.

To resolve this, simply eliminate it from your HTML code:

<label for="" class="col-sm-2 col-form-label">Name</label>
    <div class="col-sm-10">
      <label for="" class="col-sm-12 col-form-label">{{(country$ | async).countryName}}</label>
    </div>
  </div>
    <div class="form-group row">
      <label for="" class="col-sm-2 col-form-label">&nbsp;</label>
      <div class="col-sm-10">
          <button type="button" class="btn btn-success fa fa-pencil-square-o"  (click)='editCountry()' >&nbsp;Edit</button>&nbsp;
          
      </div>
    </div>
  </div>

Next, remove the parameters from your editCountry function like so:

editCountry():void{
    /** ... **/
}

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

Implementing intelligent parameter type enforcement according to configuration settings

I can't decide on a name for this concept, so please be patient while I explain it. There are three configuration objects: const configA = { type: 'A' as const, getPath: (query: { foo: string }) => `/${query.foo}` } const config ...

Angular API snapshot error: The type 'IJobs' does not match the expected type 'IJobs[]'

Currently, I am in the process of learning and attempting to construct a job board using Angular 10. Although my API setup seems to be functioning properly, when navigating to the job detail page on Chrome, an error is displayed: ERROR in src/app/job-det ...

Issue with displaying Typescript sourcemaps on Android device in Ionic 2

Encountering a strange behavior with Ionic2. After deploying my app to a simulator, I am able to view the .ts file sourceMap in the Chrome inspect debugger. In both scenarios, I use: ionic run android https://i.sstatic.net/JarmI.png However, when depl ...

Filling a data entry with simultaneous commitments

Sample code: type Alphabet = 'a' | 'b' | 'c'; const alphabetMap: Record<Alphabet, null> = { 'a': null, 'b': null, 'c': null} // Select any asynchronous processing function you prefer funct ...

"Exploring the Possibilities of Using Angular SSR to Access LocalStorage Specifically in the Browser

I've been attempting to implement Browser Storage into my Angular application with the code below: import {Inject, Injectable, InjectionToken} from '@angular/core'; export const BROWSER_STORAGE = new InjectionToken<Storage>('Bro ...

After including the material tailwind configuration in the tailwind.config file, the color options for background or border, such as zinc and many others, disappear

Do I need to make any additional configurations? const withMT = require("@material-tailwind/react/utils/withMT"); module.exports = withMT({ content: ["./src/**/*.{js,jsx,ts,tsx}"], theme: { extend: {}, }, plugins: [], }); After applying the a ...

What is the reason for receiving an error with one loop style while the other does not encounter any issues?

Introduction: Utilizing TypeScript and node-pg (Postgres for Node), I am populating an array of promises and then executing them all using Promise.all(). While pushing queries into an array during iteration over a set of numbers, an error occurs when the ...

Angular 2 template is nowhere to be found

As a newcomer to Angular 2, I am currently developing an app where I have successfully completed the Root component containing a navigation bar and footer. However, as I delve into working on the homepage module, I encountered an error. [Error] Unhandle ...

Tips for dynamically incorporating filtered selections into a Mat-Select dropdown

I am seeking guidance on how to prevent changing the values of already selected values in other rows when each row of the formArray is altered. Adding controls dynamically and correctly retrieving values in filters are functioning properly. The issue arise ...

Elementary component placed in a single line

Creating a text dropdown menu using the following code: import { Autocomplete, TextField } from '@mui/material' import React, { useState } from 'react' const options = [ 'Never', 'Every Minute', 'Every 2 ...

What are the steps to integrate <br> in a JavaScript code?

I have recently started learning about web development and I'm facing a challenge with this implementation. var obj = [[{ name: "John", age: 30, city: "New York"}, { name: "Ken", age: 35, city: "New Orleans"}]]; ...

Node_modules folder is excluded from Typescript compilation

I am struggling to understand why TypeScript is not compiling code from the node_modules folder. Below is the content of my tsconfig.json file: { "compilerOptions": { "rootDir": ".", "baseUrl": ".", "paths": { "shared": ["./src/shared ...

Angular 2: Shared functions for universal component usage

I am working on an Angular 2 webpack project and I have come across a scenario where I have some functions that are repeated in multiple components. I want to find a way to centralize these functions in a "master" class or component so that they can be eas ...

Issue found: Passing a non-string value to the `ts.resolveTypeReferenceDirective` function

Encountering the following error: Module build failed (from ./node_modules/ts-loader/index.js): Error: Debug Failure. False expression: Non-string value passed to ts.resolveTypeReferenceDirective, likely by a wrapping package working with an outdated res ...

Encountered a hiccup during the deployment of an Angular application on Heroku

I've been working on deploying an Angular app called "test-app" to Heroku via GitHub and everything seems to be going smoothly, except for setting up the express routing function. I've tried different paths, but Heroku keeps throwing this error: ...

Scaling the ion-spinner to fit your specific needs

In my Ionic application, I am utilizing the ion-spinner. However, I have encountered an issue with resizing the spinner. While custom CSS works well with default spinners, it does not function properly with Bubbles, Circles, and Dots spinners. CSS .spin ...

Preventing special characters in an input field using Angular

I am trying to ensure that an input field is not left blank and does not include any special characters. My current validation method looks like this: if (value === '' || !value.trim()) { this.invalidNameFeedback = 'This field cannot ...

The dispatch function of useReducer does not get triggered within a callback function

Can anyone assist me with this issue I am facing while using React's useReducer? I'm trying to implement a search functionality for items in a list by setting up a global state with a context: Context const defaultContext = [itemsInitialState, ...

Transforming ActivatedRoute.queryParams into a Promise

Instead of subscribing to route.queryParams as an Observable, I want it to be a Promise so that I can use async/await for function calls in ngOnInit. However, my attempt at this is not working as expected. The code below does not produce any output: constr ...

Is there a method to accurately pinpoint the specific type?

Is there a way to optimize the validateField function to narrow down the type more effectively? type TStringValidator = (v: string) => void; type TNumberValidator = (v: number) => void; type TFields = 'inn' | 'amount'; interface ...