Challenges with Converting Attribute Types in Angular Components

Currently, I am facing an issue with a component that is meant to edit an existing database listing on my fictional buy/sell app project. Upon startup, the error message I encounter is as follows:

Error: src/app/edit-listing-page/edit-listing-page.component.html:8:9 - error TS2322: Type 'number' is not assignable to type 'string'.
    [currentPrice] = "listing.price">

src/app/edit-listing-page/edit-listing-page.component.ts:9:16
    9   templateUrl: './edit-listing-page.component.html',
                    
    Error occurs in the template of component EditListingPageComponent.

I'm wondering what exactly I might be missing here. Any insights would be greatly appreciated. Thanks, Ironman

edit-listing-page.component.html

<div class="content-box" *ngIf="listing">
    <h2>Edit Listing</h2>
    <app-listing-data-form 
        buttonText="Save Changes"
        (onSubmit)="onSubmit($event)"
        [currentName]="listing.name"
        [currentDescription]="listing.description"
        [currentPrice]= "listing.price" >
    </app-listing-data-form>
</div>
<div class="content-box" *ngIf="!listing">
    <h3>Loading...</h3>
</div>

edit-listing-page.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { ListingsService } from '../listings.service';
import { Listing } from '../types';

@Component({
  selector: 'app-edit-listing-page',
  templateUrl: './edit-listing-page.component.html',
  styleUrls: ['./edit-listing-page.component.css']
})
export class EditListingPageComponent implements OnInit {
  listing: Listing;
  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private listingsService: ListingsService,
  ) { }

  ngOnInit(): void {
    const id = this.route.snapshot.paramMap.get('id');
    this.listingsService.getListingById(id) 
      .subscribe(listing => this.listing = listing);
  }

  onSubmit({name, description, price}):void{
    alert('Saving changes to the listing...');
    this.listingsService.editListing(this.listing.id, name, description, price)
      .subscribe(() => {
        this.router.navigateByUrl('/my-listings');
      });
    
  }
}

types.ts

export interface Listing{
    id: string,
    name: string,
    description: string,
    price:number,
    views: number,
};

listings.service.ts

 editListing(id:string, name:string, description:string, price:number): Observable<Listing>{
    return this.http.post<Listing>(
      `/api/listings/${id}`,
      {name, description, price }, 
      httpOptions,
    );
  }

listing-data-form.component.ts

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { Router } from '@angular/router';
import { Listing } from '../types';

@Component({
  selector: 'app-listing-data-form',
  templateUrl: './listing-data-form.component.html',
  styleUrls: ['./listing-data-form.component.css']
})
export class ListingDataFormComponent implements OnInit {
  @Input() buttonText;
  @Input() currentName = '';
  @Input() currentDescription= '';
  @Input() currentPrice= '';
  name:string = '';
  description:string = '';
  price:string = '';

  @Output() onSubmit = new EventEmitter<Listing>();

  constructor(
    private router: Router,
  ) { }

  ngOnInit(): void {
    this.name = this.currentName;
    this.description = this.currentDescription;
    this.price = this.currentPrice;
  }

  onButtonClicked(): void{
    this.onSubmit.emit({
      id: null,
      name: this.name,
      description: this.description,
      price:Number(this.price),
      views: 0,
    });
  }

}

listing-data-form.component.html

<div>
        <label for="price">
            Price:
        </label>
        <input id="price" name="price" type="text" [(ngModel)] = "price" />
    </div>
        <button type="submit">{{buttonText}}</button>

Answer №1

Open your listing-data-form.component.ts file

@Input() currentPrice= '';
  ...
  price:string = '';

It should look like this:

@Input() currentPrice= 0;
  ...
  price:number = 0;

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

Transforming a Bootstrap 4 HTML project into Angular 9

After stumbling upon a beautiful HTML template that caught my eye, I realized it was built using Bootstrap. Luckily, I came across tutorials on how to convert such templates into Angular 6 projects, making the process seem quite straightforward (like this ...

Issue when rendering <options> while looping through country object in the country list

To retrieve a list of all countries in my React project written in TypeScript, I am utilizing the countries-list library which can be found here. My intention is to create a <Form> that includes a <Select> dropdown menu populated with the coun ...

Issue with Angular/Chrome: The filter pipe is not able to be located

Even though this topic has been covered before, I have not found any satisfactory solutions. Here is my approach: play.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; impor ...

Integrating React frontend with Node JS backend on Kubernetes platform

Seeking guidance on the best approach for making API requests from a React Frontend Application to a Node JS backend application in a Kubernetes environment. Both are hosted within the same container, following this dockerfile structure: COPY frontend/pack ...

When utilizing Typescript with React Testing Library, the error message "Using 'SidebarItem' as a value instead of a type. Perhaps you meant 'typeof SidebarItem'?" (ts(2749)) is encountered

I am currently in the process of creating a test for a basic React component using Jest + RTL. Here is the code snippet of the component: import React from 'react'; import ListItem from '@material-ui/core/ListItem'; import ListItemTex ...

Filtering data based on button value with AngularJS click event

Is there a way to filter data based on a fixed button value in Angular JS? Specifically, I want to display only the data related to the "veg" category when the "veg" button is clicked. I am still new to learning Angular JS and could use some guidance with ...

displaying html depending on certain conditions

My goal is to display different HTML text based on the if conditions in my component.ts file. Here is a snippet of my HTML code: <div class="login"> <div *ngIf="emailStatus == EmailStatus.verified"> <h1>You ...

A guide on how to navigate to a customizable element in React Native

After creating a glossary, I needed a way to access the content of a specific letter by clicking on that letter from a list displayed at the top of my page. However, I encountered an issue - while I managed to implement scrolling functionality, I couldn&ap ...

Effectively enhance constructor by incorporating decorators

Is it possible to properly extend a class constructor with decorators while maintaining the original class name and static attributes and methods? Upon reading the handbook, there is a note that cautions about this scenario: https://www.typescriptlang.or ...

Utilizing HTML Loops along with Conditional Statements

I am working with Ionic2/Angular2 and have a collection of messages that I iterate through to display their details. <div *ngFor="let message of messages" class="message-wrapper"> <div *ngIf="!exists(message)"> <div *ngIf="message.cha ...

Exploring Angular: A Guide to Localisation and JSON

Looking at my JSON database structure below: { "users" : { "-Kowtg5yyK-DTIz91cQ8" : { "language" : "en", "uid" : "kNyDJnktxyakL6owhGd1rruGACb2", "userName" : "admin" } }, "localisation" : { "login" : { "en" : "Log ...

Invalid action has been dispatched by the effect:

In my project, I am using Angular 7.1.4. This is an excerpt from my effect code: @Injectable() export class LoginEffects { constructor(private actions$: Actions, p ...

Utilizing React Typescript to dynamically render a duo of components

On a single page, I want to display two components simultaneously. There is a bottom navbar that, when clicked on, for example the profile icon, should render the profile page. However, I would like to change the color of the icon based on which component ...

changing the order of items in a list when using ngFor

I'm currently working on setting up a list-group with list-group-items, but I've encountered a CSS issue caused by Angular when using ngFor on the list-group items. It seems like Angular automatically assigns the bootstrap classes .list-group-it ...

Positioning a Box tag at the bottom using MUI 5

My goal is to position a Box tag at the bottom of the page. Current Behavior: https://i.stack.imgur.com/ZupNo.png I am looking to place a TextField and send button at the bottom of the page on both browser and mobile. I want user messages to be above th ...

Angular 5 Function Formatting Guide

While studying the code that showcases a class in Angular 5, I came across this snippet: export class HeroService { constructor() { } getHeroes(): Hero[] { return HEROES; } } I'm puzzled about the significance of the : Hero[] section wi ...

Angular application designed to identify the origin of the user

I am managing 3 distinct angular applications, each with its own unique URL. Login application Launcher application Content application Users are required to navigate through the applications in the following sequence: login > launcher > content. W ...

Array class injection

I have developed a class called MetaManager: @Injectable() export class MetaManager{ constructor(private handlers:Handler[]){ console.log(handlers); } } This class requires a Handler[] to be registered as handlers. When I receive some me ...

Creating storage solutions for an Angular 2 application

Utilizing localStorage in an authentication service within my app, I am currently in the process of transitioning the old app to a new project structure with webpack. While each app has its own unique package.json file, I am unsure about the specific node ...

Unexpected directory structure for internal npm module

Here is the package.json I use for building and pushing to an internal package registry: { "name": "@internal/my-project", "version": "0.0.0", "description": "Test package", "type&quo ...