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" #codeRequest="ngModel" [(ngModel)]="requestModel.codeRequest" id="codeRequest" name="codeRequest"/>
 </form>

 <button (click)="func()"> </button>

Code Snippet :

@ViewChild('form') form: ElementRef;
  constructor(){}

  func(){
    this.formStep2.nativeElement.submit();
  }

  submitForm(form: NgForm) {
    ... 
  }

What might be causing my issue?

Answer №1

When it comes to submitting a form with a button (type=submit) that is located outside the form, you have several options:

Start by defining a model:

export interface Student {
  id: number;
  name: string;
}

In your app.component.ts file:

public model: Student;

@ViewChild('form', { read: NgForm }) form: any;

ngOnInit(): void {
  this.setDefaultValueForModel();
}

saveForm($event: Event) {
  $event.preventDefault();

  if (this.form.valid) {
     console.log(this.form.value);
     alert('valid');
   } else {
     alert('invalid');
   }
}

setDefaultValueForModel() {
  this.model = {
    id: 0,
    name: ''
  };
}

Now, in your app.component.html file:

<form #form="ngForm" novalidate id="ngForm" (submit)="saveForm($event)">
  <div class="form-group">
    <label>Name</label>
    <input type="text" required name="name" [(ngModel)]="model.name" #name="ngModel">
    <p *ngIf="name.invalid && name.touched">
      Name is required.
    </p>
  </div>
</form>

<div>
  <button type="submit" form="ngForm" [disabled]="!form.form.valid">
    Save
  </button>
</div>

VIEW DEMO

Answer №2

When you need to submit a form by clicking a button located outside the form, follow this example:

Here is the HTML structure for your view:

<div >
  <button (click)="onSubmit()">Submit from outside</button>

  <form [formGroup]="fooForm" (ngSubmit)="onNgSubmit()">
    <label>Label One:</label>
    <input formControlName = "fieldOne">

    <label>Label Two:</label>
    <input formControlName = "fieldTwo">

  </form>
</div>

In the controller, remember to call the method tied to the ngSubmit event when the button is clicked.

export class YourComponent  {
  public fooForm: FormGroup;

  ngOnInit(){
    this.fooForm = new FormGroup({
      'fieldOne':new FormControl('value-one'),
      'fieldTwo':new FormControl('value-two')
    });
  }

  public onSubmit(){
    console.log("submitting from outside the form");
    this.onNgSubmit();
  }

  public onNgSubmit(){
    console.log(this.fooForm.value);
  }
}

Visit stackblitz for a live demo

Answer №3

One simple way to include the button within the form is as follows:

If you prefer a different button placement, you will need to explore other options.

Utilize reactive forms in your code to optimize functionality.

submitForm(){ 
    if(this.myReactiveForm.valid){ 
        const formValues = this.myReactiveForm.value;
        this.http.post(url,formValues).subscribe(response => { ... })
    }
}

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

What is the best way to show the previous month along with the year?

I need help with manipulating a date in my code. I have stored the date Nov. 1, 2020 in the variable fiscalYearStart and want to output Oct. 2020. However, when I wrote a function to achieve this, I encountered an error message: ERROR TypeError: fiscalYear ...

Issue with minifying AngularJS and TypeScript route configuration for safe minification

Currently, I have a package containing multiple js files that were created from typescript files. However, when I attempt to apply minification to the package, the webpage encounters errors. The error message displayed on the Chrome console is: Uncaug ...

How is it possible for TypeScript to enable the importing of dependencies that it ultimately cannot utilize during runtime?

Take a look at my sample project by following this link: https://github.com/DanKaplanSES/typescript-stub-examples/tree/JavaScript-import-invalid I have developed a file named main.ts: import uuid from "uuid"; console.log(uuid.v4()); While type ...

What could be the reason behind the frequent appearance of multiple calls in Fiddler upon initiating a SignalR connection

As I set up a signalr connection from my angular front-end to an Asp.Net Core back-end, multiple calls are being made when starting the connection. The issue arises with the first call not completing, which poses a problem for our end-to-end tests. Attemp ...

Brand new Angular 9 application encountering the error message "ERROR in Cannot read property 'flags' of undefined" when running "ng build" on a Mac device

I set up a fresh Angular 9 project on my MacBook by executing ng new demo (no routing, CSS) cd demo ng build However, I encountered the following error: ERROR in Cannot read property 'flags' of undefined When running "ng version", here's ...

Tips for avoiding dual API calls in Angular

How can I avoid making two API calls in Angular? I have a function that is called twice in ngOnInit, but I want it to only execute once when the id changes from the URL parameter. However, both functions are being invoked when the page is loaded for th ...

Tips for creating spacing between an image and a button when utilizing the routerLink feature in CSS

To enhance the user interface, I've utilized a routerLink with an image to navigate back to the home page, and a button to direct users to add a new customer. Now, I am aiming to create some space between these elements. Previously, I used "& ...

How to open a PDF file in a new tab using Angular

Within my Angular 12 application, I am seeking to enable users to "view" a PDF file stored locally in the application within a new tab on Google Chrome. Currently, when implementing the code below in HTML, the file downloads rather than opening in a new ta ...

Unable to retrieve shared schema from a different schema.graphql file within the context of schema stitching

In my project, I have a user schema defined in a file named userSchema.graphql; id: String! userName: String! email: String! password: String! } In addition to the user schema, I also have separate schema files for login and register functionalit ...

Prevent selection of past dates and times in ng-bootstrap calendar in Angular 7

HTML <ngb-datepicker (select)="onDateSelect($event)" [(ngModel)]="datePickerModel"></ngb-datepicker> <ngb-timepicker [meridian]="meridian" [(ngModel)]="time" class="fromTimePick"> </ngb-timepicker> Is it possible to restrict the ...

Angular 2 Typeface Delivery to the Server

I'm experiencing an issue with the font when trying to access it from the server. It works fine on localhost, but on the server with a different directory structure, it fails to load properly. The same problem occurs with the logo as well. @font-face ...

Unveiling the Swiper Instance with getSwiper in Ionic5 and Angular

Currently, I am integrating ion-slides into my Ionic 5 project built with Angular. In accordance with the instructions provided in this documentation, I aim to retrieve the Swiper instance by utilizing the getSwiper method so that I can leverage the functi ...

Making an API request at regular intervals of x seconds

I am currently working on an Angular chat application where I need to fetch new messages at regular intervals. The time intervals for fetching new messages are as follows: 1. Every 5 seconds 2. Every 10 seconds 3. Every 20 seconds (if there are new message ...

Converting the following ngRx selector to a boolean return – a guide

I am currently using the following filter to retrieve a list of data within a specific date range. I have implemented logic in the component where I check the length of the list and assign True or False to a variable based on that. I am wondering if ther ...

Youngster listens for guardian's occurrence in Angular 2

While the Angular documentation covers how to listen for child events from parents, my situation is actually the opposite. In my application, I have an 'admin.component' that serves as the layout view for the admin page, including elements such a ...

The submit button is getting disrupted by the background image being set

Implement the following CSS code to set a background image on a single-page app (Angular). .page::before { content: ''; position: absolute; background-size: cover; width: 100%; height: 100%; background-image: url("../../assets/weird. ...

Passing a value to a property with a dynamically passed name in TypeScript

I'm encountering an eslint/typescript error message: errorUnsafe member access .value on an any value @typescript-eslint/no-unsafe-member-access when attempting to assign a value to a dynamically named property: selectChange(name: string, value: stri ...

The Replay Subject will not activate the async pipe when utilizing the subscribe shorthand during initialization

I'm curious about the behavior of a replay subject created using the subscribe shorthand method, specifically why it does not trigger the async pipeline when the next method is called. When I follow this approach, everything functions as expected: ex ...

typescript dispatch issue

Whenever I attempt to send this dispatch, it consistently results in the following error message (and the same issue occurs with all my other dispatches): The argument of type '(dispatch: Dispatch) => Promise' is not compatible with a paramet ...

Tips for integrating Tesseract with Angular 2 and above

I'm currently exploring the use of Tesseract within one of my components for OCR processing on a file. .ts: import * as Tesseract from 'tesseract.js'; fileToUpload: File = null; handleFileInput(files: FileList) { this.fileToUpload = f ...