Running JavaScript code in a TypeScript component can be achieved by leveraging the interoperability features

I am currently diving into Angular and tackling a project using Angular 5 (TypeScript). I find myself in need of a JSON validator function that checks if the given JSON is in the correct format. I stumbled upon a function on the internet, but it's written purely in JavaScript.

I want to integrate this function into my component. Essentially, it should validate whether the provided JSON is formatted correctly or not.

<textarea ng-change="updateJsonObject()" ng-model="script" rows="10" 
 class="form-control" style="width: 100%" ng-style="formatting"> 

    var app = angular.module("app", []);

app.controller("mainController", function($scope) {
  $scope.formatting = {color: 'green', 'background-color':'#d0e9c6'};
  $scope.message = {
                BasketCost: '5.00',
                Fruit: ['Apple', 'Orange', {Name: 'Pear', Expires: '15/05/17'}],
  };

  $scope.isValid = true;

  $scope.script = JSON.stringify($scope.message);

  $scope.updateJsonObject = function() {
    try {
      JSON.parse($scope.script);
    } catch (e) {
      $scope.isValid = false;
      $scope.formatting = {color: 'red', 'background-color':'#f2dede'};
    }

    $scope.message = JSON.parse($scope.script);
    $scope.isValid = true;
    $scope.formatting = {color: 'green', 'background-color':'#d0e9c6'};
  };
});

What is the steps required to incorporate this code into my component.ts file?

Answer №1

To access the given URL, simply click on this link: https://stackblitz.com/edit/angular-8jjx4b

When dealing with immediate changes, remember to utilize ngModelChange in your code.

<textarea (change)="updateJsonObject()" (ngModelChange)="updateJsonObject()" [(ngModel)]="script" rows="10" 
class="form-control" style="width: 100%" [ngStyle]="formatting"></textarea>    

// within the class

message = {
    BasketCost: '5.00',
    Fruit: ['Apple', 'Orange', { Name: 'Pear', Expires: '15/05/17' }],
};

isValid = true;

// script = '{' + JSON.stringify(this.message) + ')'; // testing
script = JSON.stringify(this.message);


formatting = { color: 'green', 'background-color': '#d0e9c6' };


ngOnInit() {
    this.updateJsonObject();
}

updateJsonObject() {
    try {
        JSON.parse(this.script);
        this.formatting = {color: 'green', 'background-color':'#d0e9c6'};
        console.log('invalid');
    } catch (e) {
        console.log('invalid');
        this.isValid = false;
        this.formatting = {color: 'red', 'background-color':'#f2dede'};
    }
}

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

When using Angular SSR, the transferState.get(key, null) method may return null even though objects are visible when logged (both in the browser)

While working on my Angular application, I've noticed a flicker when simulating a mid-tier mobile browser. It seems like Angular is not properly rehydrating the DOM when transitioning from Server to Browser, resulting in a full replace of the DOM. Th ...

Error is being thrown due to defining a variable after it has already been declared and

Before I use a variable, I encountered the issue of using it before its definition, interface IProps extends WithStyles<typeof STYLES>; const STYLES = () => ({ }) Although it didn't cause any errors, a warning appeared: STYLES used befo ...

What sets apart Object.assign {} from Object.assign []?

While reviewing code done by a previous developer who is no longer with us, I observed that they sometimes used Object.assign({}, xyz) and other times they used Object.assign([], abc); Could there be a distinction between the two methods? ...

Ionic 2: Unveiling the Flipclock Component

Can anyone provide guidance on integrating the Flipclock 24-hours feature into my Ionic 2 application? I'm unsure about the compatibility of the JavaScript library with Ionic 2 in typescript. I have searched for information on using Flipclock in Ionic ...

Ways to display the chosen value based on the item's index using Javascript in Angular

If you want to view the complete code, just click on this link. I have identified the main issue here. Check out the code here: https://stackblitz.com/edit/test-trainin-2?file=src/app/app.component.html The problem is when you interact with the green bal ...

Ways to remove options from a select dropdown

I've encountered an issue with my design that involves adding and removing chips on a page using dropdown selection. Despite being able to remove a chip by clicking on it, I'm unable to clear the value of the select element no matter what methods ...

Volta alert: Temporary directory creation failed

Recently, I attempted to globally download and install TypeScript using the npm install -g typescript command in my terminal. Unfortunately, an error occurred: Volta error: Could not create temporary directory in /Users/username/.volta/tmp/image/packages ...

Is Highcharts-angular (Highcharts wrapper for Angular) compatible with Angular 4?

I have attempted to install various versions of highcharts-angular, ranging from 2.0.0 to 2.10.0. However, I consistently encounter the same error when running the application. The error message states: Metadata version mismatch for module C:/dev/Angular- ...

Having trouble with error popups in Typescript 3.7.2, React, and Material UI 4.5.1 Snackbars due to styling errors

Utilizing the material UI snackbar for displaying error pop-ups in my react application has been quite a challenge. Incorporating a container view where certain actions trigger errors, I aimed to implement my custom snackbar component when an error arises ...

Creating a dynamic user interface in Angular 6 that successfully tracks changes without reliance on the parent

As I delve into the world of Angular, I am faced with a challenge in creating a reusable component that will be bundled into an npm module. The issue lies in the UI change detection aspect. In order for the component to function properly, the application ...

Using boolean value as default input value in React

When trying to set the default value of a controlled checkbox input from my request, I encountered an error stating "Type 'boolean' is not assignable to type 'string | number | readonly string[] | undefined'". Do you have any suggestion ...

Unsteady movement of Three JS OrbitControls during rotation

Currently, I am working on a scene with three.js and using orbit controls to rotate the camera around the scene. Occasionally, while rotating, the camera starts moving erratically before calming down and rotating smoothly again. I have read about orbit co ...

Proper positioning of popover ensures it does not exceed the boundaries of its parent

In my ngprime table, the header row contains a column field with a popover set to display at the top. However, it is covering the actual field instead of appearing above it. This issue arises because the popover cannot display outside of its parent div, ca ...

Angular 7: How to Ensure Your Video's Current Time is Always 0

I am trying to adjust the playback of my video using a range input, but I am encountering an issue. Even when I set video.currentTime to 2, it remains stuck at 0 and the value never changes. Below is the code snippet from my angular 7 project: index.co ...

Discover the key to ensuring that optional peer dependencies are genuinely optional

My NPM package offers both core functionality in the form of React hooks and UI components that utilize these core features. Originally, I planned to create two separate packages - one for the core functionality and another for the components. However, upo ...

Angular: defining a new class instance and implementing various services

Creating a class called User raises the concern of having access to services within it, especially when using the constructor() for dependency injection. Below is an implementation of the User class: import { ElementRef, Injectable } from '@angular/ ...

Solutions for repairing data storage variables

I am trying to access the value dogovor from session_storage and assign it to variable digi. However, I seem to be encountering an issue with this process. Can anyone help me identify where I am going wrong? loadCustomer(){ return new Promise(resolve =& ...

Passing a value from an HTML template to a method within an Angular 4 component

Encountering an issue with Angular 4. HTML template markup includes a button: <td><a class="btn btn-danger" (click)="delete()"><i class="fa fa-trash"></i></a></td> Data is assigned to each td from a *ngFor, like {{ da ...

A declaration file for the module 'module-name' was not found. The file '/path/to/module-name.js' is assumed to have a type of 'any' by default

After diving into the inner workings of TypeScript module resolution, I stumbled upon an issue. Within my repository @ts-stack/di, the directory structure post-compilation looks like this: ├── dist │   ├── annotations.d.ts │   ├─ ...

Utilize the identical element

Incorporating the JwPaginationComponent into both my auction.component and auctiongroup.component has become a necessity. To achieve this, I have created a shared.module.ts: import { NgModule } from '@angular/core'; import { JwPaginationCompon ...