The formio onchange event may result in an undefined object

Encountering an issue here:

Error: src/app/app.component.html:1:30 - error TS2532: Object is possibly 'undefined'.

1 <form-builder [form]="form" (change)="onChange($event)"></form-builder>

while working on my form-builder. I suspect the (change) to be the culprit, but honestly, I am unsure how to resolve it

Answer №1

import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';

@Component({
  selector: 'app-form-crear',
  templateUrl: './form-crear.component.html',
  styleUrls: ['./form-crear.component.scss']
})
export class FormCrearComponent implements OnInit {
  @ViewChild('json') jsonElement?: ElementRef | any;
  @ViewChild('formio') formio:any;
  public form: any = {
    components: [

    ]
  };


  ngOnInit(): void {
      
  }

  saveForm(){
    this.jsonElement.nativeElement.innerHTML = '';
    this.jsonElement.nativeElement.appendChild(document.createTextNode(JSON.stringify(this.formio.form, null, 4)));

    const json = document.createTextNode(JSON.stringify(this.formio.form, null, 4));
  }

}
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <form-builder [form]="form" #formio></form-builder>
        </div>
    </div>
    <hr class="linea">
    <button (click)="saveForm()">View Form</button>
    <div class="well jsonviewer">
        <pre id="json"><code class="language-json" #json></code></pre>
      </div>
</div>

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

The functionality of Angular router.navigate is not supported within Material Autocomplete

Currently, I am working on developing an autocomplete feature for a search functionality that allows users to look up products and navigate to a single product page by clicking on a specific product with its ID in the URL. To implement this, I am using An ...

Tips for accessing a Literal type in TypeScript instead of a Union type

I recently developed a function to generate dynamic elements. However, I encountered an issue where instead of returning the precise type of the element, it was producing a union of various <HTMLElementTagNameMap> types. function createCustomElement( ...

transforming an angularJS directive into an angular6 component/directive

I have inherited an angularJS directive from an old application that I need to convert to angular6. Since I am not familiar with angularJS and only work with angular6, I am seeking guidance on how to proceed. Below is the existing angularJS code: define ...

Add a new class to clr-tab

Currently, I am attempting to display Clarity tabs in a horizontal layout as opposed to the vertical layout due to the unavailability of vertical tabs. Just to clarify, the links are displayed vertically while the main structure consists of horizontal link ...

Resetting and marking an Angular2 form as untouched

Is it possible to reset a form and mark it as untouched, clean, etc after submission while staying on the page to avoid resubmission? this.myForm.reset() this.myForm.markAsPristine() this.myForm.controls['options_name'].markAsUntouch ...

Converting an array of object values to an Interface type in Typescript

In my JSON document, I have an array named dealers that consists of various dealer objects like the examples below: "dealers" : [ { "name" : "BMW Dealer", "country" : "Belgium", "code" : "123" }, { "name" : ...

There seems to be a syntax error in the regular expression used in Angular TypeScript

I've encountered an error and I'm struggling to identify the syntax issue. core.mjs:6495 ERROR SyntaxError: Invalid regular expression: /https://graph.microsoft.com/v1.0/communications/callRecords/getPstnCalls(fromDateTime=2020-01-30,toDateTime ...

I'm facing an issue where I am unable to commit the Angular folder in my project using IntelliJ or SourceTree with

I am currently working on a web app project that includes a folder with a PHP API REST and another folder with Angular files. Strangely, when I try to commit my files to BitBucket, everything gets committed except the files under the Angular folder. Simil ...

Utilize [markdown links](https://www.markdownguide.org/basic-syntax/#

I have a lengthy text saved in a string and I am looking to swap out certain words in the text with a highlighted version or a markdown link that directs to a glossary page explaining those specific words. The words needing replacement are contained within ...

Matching TypeScript values and types does not function as intended

Recently, I delved into TypeScript to work on my new AngularJS project. However, I encountered an issue where the id, which is supposed to be of type number, is actually being treated as a string. Have I overlooked something in my code? interface IRout ...

Can you explain the significance of using curly braces in an import statement?

The TypeScript handbook has a section on Shorthand Ambient Modules, where an import statement is shown as: import x, {y} from "hot-new-module"; It doesn't explain why y is in curly braces in the above statement. If both x and y were inside the brace ...

Challenge encountered with implementing Next-Auth's authorize function in TypeScript

Encountering a type error in the authorize function while using NextAuth with CredentialsProvider export const authOptions : NextAuthOptions ={ session : { strategy: "jwt" }, providers : [ CredentialsProvider({ async authorize( c ...

Can a form be submitted using ViewChild in Angular5?

Can a form be submitted using ViewChild in Angular5? If so, how can it be achieved? I attempted to do this but was unsuccessful My Attempt: <form #form="ngForm" (submit)="submitForm(form)" novalidate> <input required type="text" #codeReques ...

Typescript excels at gracefully handling cases where an element is not found

While working with Typescript-Protractor Jasmine, I encountered an issue where the test case (the 'it' block) is not failing when an element is not found. Instead, it shows an UnhandledPromiseRejectionWarning but still marks the script as passed. ...

Animating with Angular 2

As I delve into this informative resource, my goal is to incorporate some animations into my applications, but I find myself grappling with understanding how the animations are triggered. HTML Component <div class="navbar navbar-default navbar-fixed-t ...

Instructions for making a vertical arbitrary line on a financial graph

I came across this example on a website and it's functioning perfectly. The code creates a vertical line at the specified index location when x and y values are passed separately. example() { var originalLineDraw = Chart.controllers.line.prototype ...

Angular error message: Trying to access the property 'name' of an undefined object leads to a TypeError

I'm having trouble phrasing this question differently, but I am seeking assistance in comprehending how to address this issue. The error message I am encountering is as follows: TypeError: _co.create is not a function TypeError: Cannot read property ...

The issue of the mat-select change event failing to trigger in an Angular 13 reactive form when using the

How to use mat-select within a form-group <mat-form-field appearance="outline"> <mat-select formControlName="formula" id="formula"> <mat-option [value]="metricFormula.TotalCount">{{l(&apos ...

Solving the issue of interconnected promises in Angular services

I am utilizing a DynamoDB service within my Angular project which returns a promise through a series of promises. This process involves retrieving a subId from Cognito and then passing that subId to a DynamoDB get query: async getUserObject(): Promise< ...

What is the reason behind the narrowing of the type by indexing into a mapped type?

This question is inspired by an amazing answer found here: My curiosity lies in why the indexing works in the mapped type trick. Let's illustrate with an example: type MyData = { a: { alpha: string; }; b: { beta: number; } } type ...