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?