Exploring an array in Angular 2 using TypeScript

Just starting out with typescript and angular2 and working through some issues. I have a form that needs to display results from an array of changing items, so I don't know the exact index of each result.

Here is my scenario:

In my form.html file:

<span style="color:red">{{usererror.username}}  </span>
...other items here
<span style="color:red">{{usererror.password}}  </span>

And in the component:

export class LoginComponent implements OnInit{
 public usererror={
    username:"",
    password:""
  }

  //this function is called after a post request
onLoginError(error:any){

let message= JSON.parse( error._body);
  console.log(error._body); //first log
  console.log(message)  //second log


}

}

When calling the above function, the first log returns an array like this:

[{"field":"username","message":"Username cannot be blank."},
  {"field":"password","message":"Password cannot be blank."}]

My goal is to assign the username and password variables in usererror based on the returned messages for them to be displayed. However, sometimes the returned results may not include one field or the other. Currently, I am trying to iterate through the message array but facing challenges due to missing fields. Any suggestions would be appreciated as I am still new to angular2 and typescript.

Answer №1

Ensure to utilize square brackets when accessing object properties (object["property"]):

let errorMessages = JSON.parse(error._body);
for (let errorMessage of errorMessages){
    if(this.userErrors[errorMessage.field]){
        this.userErrors[errorMessage.field] = errorMessage.message;
    }
}

Answer №2

In order to ensure that the message contained in this.usererror.message[i].field exists before attempting to duplicate it, you can implement an if condition as shown below:

for (var i=0; i<message.length; i++){
    if(this.usererror.message[i].field){
        this.usererror.message[i].field = message[i].message;
    }
}

If the field is undefined, indicating that it does not have a value, then the if statement will evaluate to false.

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

"Production mode is experiencing a shortage of PrimeNG(Angular) modules, while they are readily accessible in development

I've been diligently working on an Angular application that heavily relies on PrimeNG as the UI component framework. Initially, I had no issues deploying my app with Angular version 9 and PrimeNG version 8. However, a while ago, I decided to upgrade t ...

Listening for button clicks in a Bootstrap drop down menu using JavaScript

I'm struggling to figure out how to detect button clicks in a drop-down menu. I've tried using Array.from to assign an event listener to each button in the drop-down, but it doesn't seem to work efficiently. It feels inefficient to assign in ...

What is the reason for instanceof Map returning false?

Utilizing the Draft.js plugin called Mention. When accessing editorState.content.entityMap.mention, I am able to retrieve the value by: mention.get('address') However, when I attempt to verify if it is a Map using: console.log('mention&a ...

Steps to send a table to PHP and store it as a text file

I have this program for a form data entry. It includes text boxes to input values, and upon clicking 'Submit', the input values should be displayed below while resetting the text box for another set of inputs. The issue I am facing is with the sa ...

Specify the versions of packages in your package.json file

My package.json file contains many dependencies with "*" as the version, which I have learned is not recommended. I want to update them all to their latest versions. Despite using npm-check-updates tool, it indicates that all packages are up-to-date. Can ...

Encountering errors while running Angular 8's ng build prod command

After successfully migrating my project from Angular 7 to Angular 8, I encountered an issue when attempting to run 'ng build prod' which resulted in the following error: ERROR in Error during template compile of 'Ng2CompleterModule' Cou ...

What is the reason for adding CSS styles to a JavaScript file without importing them?

/Navbar.js/ import './navbar.scss'; import {FaBars, FaSearch} from "react-icons/fa"; import { useState } from 'react'; function Navbar(){ const [hide,sethide] = useState(true); const barIcon = document.querySelectorAl ...

Conceal and reveal text with a simple user click

Currently, I am working on a website project that utilizes bootstrap. However, I am facing some uncertainty regarding how to effectively hide and display text: <nav class="navbar navbar-light" style="background-color: #e3f2fd;"> ...

Updating a List Conditionally in React

Hello there! I am relatively new to the world of React and currently trying to grasp the concept of modifying elements within a list. Below, you'll find a straightforward example that illustrates my current dilemma. const numbers = [1, 2, 3, 4, 5]; / ...

Adjust the height of a div using jQuery animate based on the amount of text within

I have created a basic animation feature where users can click on an expanding box. I am looking for a solution that does not involve using a plugin. Currently, the code looks like this: $('#one').css("height", "22"); $('#t1').cli ...

The combination of AddEventListener in the parent and postMessage in the iframe is ineffective

As I delve into the Stripe documentation to develop a new feature, I have encountered an issue regarding the communication between a webpage and an iframe. The code in index.html: <!DOCTYPE html> <body> parent<br> <iframe src="./ ...

Display Google font as SVG path but encapsulate within a promise

I'm facing an issue with the following script, where it performs an async operation. My goal is to wrap it in a promise, but I'm unsure about the right approach. static convertGoogleFontToSVG(): Promise<string> { const url = 'htt ...

What is the best way to activate a file input element in my component and define the accepted file types at the same time?

My goal is to display a file upload dialog when a specific option is selected from a drop-down menu using ng-select. Each menu option corresponds to different file types, such as PDFs. Initially, I attempted to achieve this directly within the ng-select ta ...

What is the process for setting up a signup and sign-in page in Angular 12 while incorporating local storage for authentication?

After saving signup data using local storage, I am now looking to utilize that information on the login page for user authentication. What specific code should be implemented on the login page in order to verify whether the individual has signed up or no ...

Displayed in the xmlhttp.responseText are the tags

Why do tags appear when I input xmlhttp.responseText into my textbox? It displays <!DOCTYPE html><html><body></body></html> along with the desired content. Is there a way to prevent the tags from being displayed? Here is the ...

Why does the image return an Undefined Value when clicked? Is there a solution to this issue?

Every time I click on an image, I encounter the error message "undefined." Can someone please shed some light on why this is happening and provide guidance on how to successfully retrieve and pass the value to the onclick function in this particular scen ...

Add design to the footer during a specific event using Javascript

Here is the CSS code I am working with: .footer { font-family: "lato", sans-serif; padding: 20px; line-height: 1.2; text-align: right; background: #eee; color: #0D47A1; font-size: 13px; height: 80px; position: fixed; right: 0px; botto ...

Accessing data from an API using Node.js

I'm currently working with Node.js and trying to retrieve the city name from an API. However, I keep encountering an error message that reads "Cannot read property city_name of undefined." The issue seems to be arising from this specific line of code ...

How to Trigger a Child Component Function from a Parent Component in React.js

I want to trigger a function in my child component when a button is clicked in the parent component. Parent Component: class Parent extends Component{ constructor(props){ super(props); this.state = { //.. } } ...

Sorry, but React does not accept objects as valid children. Make sure the content you are passing is a valid React child element

I encountered an issue with rendering on a screen that involves receiving an object. The error message I received is as follows: Error: Objects are not valid as a React child (found: object with keys {_U, _V, _W, _X}). If you meant to render a collection o ...