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 reason for the inclusion of information in the error log by the `ng

After initiating a production build with the command ng build --configuration production, Angular logs some information to the error log: - Generating browser application bundles (phase: setup)... ✔ Browser application bundle generation complete. ✔ Bro ...

Retrieve the radio button value without using a key when submitting a form in JSON

Looking to extract the value upon form submission in Angular, here is the code: In my Typescript: constructor(public navCtrl: NavController, public navParams: NavParams, public modalCtrl: ModalController, public formBuilder: FormBuilder, public alertCtrl ...

Having trouble typing computed values in Vue Composition API with TypeScript?

I'm attempting to obtain a computed value using the composition API in vue, and here is the code I am working with: setup() { const store = useStore(); const spaUrls = inject<SpaUrls>('spaUrls'); const azureAd = inject<AzureAd ...

Is it necessary to manually unsubscribe from observables in the main Angular component?

I'm facing a dilemma with my Observable in the root Angular (6.x) component, AppComponent. Typically, I would unsubscribe from any open Subscription when calling destroy() using the lifecycle hook, ngOnDestroy. However, since the AppComponent serv ...

What is the best way to retrieve the final value stored?

This is how I am using my Selector:- private loadTree() { this.loading = true; this.store.select(transitionListSelector).pipe().subscribe(data => { console.log(data); data.map(item => { console.log(item); this.tr ...

Unable to play audio src in Angular 2 due to http request issue

The data I gathered and included in the audio source is not playing. component.detail.ts export class DetailComponent implements OnInit { @Input() detailName: string; @Output("playnhac") play = new EventEmitter(); private mp3Link:string; ...

Discovering Angular 2 Service Change Detection

Exploring the Angular 2 beta has led me to some challenges with understanding the change detection mechanism. I have put together a simple Plunker example that demonstrates an issue I am encountering. //our root app component import {Component, Injectab ...

Transform a 3D text rotation JavaScript file into an Angular component tailored TypeScript file

I have a javascript file that rotates text in 3D format, and I need help converting it into an Angular component specific TypeScript file. You can find the codepen for the original JavaScript code here. Below are my Angular files: index.html <!doctyp ...

Parsing the header parameter in a GET request from Angular within the Spring backend

Recently, I delved into Rest services in Spring and learned from a tutorial that sending parameters to the backend can be done securely through the following method: getCompanyDetails(username:string): Observable<CompanyObject>{ const headers = ...

Filtering data in an antd table by searching

Just starting out with React hooks, specifically using TypeScript, and I'm struggling to implement a search filter with two parameters. Currently, the search filter is only working with one parameter which is 'receiver?.name?'. However, I wo ...

What distinguishes Angular directives as classes rather than functions?

When using Ng directives within HTML tags (view), they appear to resemble functions that are called upon rather than instances of a class. It almost feels like they could be static methods that can be invoked without an instance of a class. Comin ...

Collaborate and apply coding principles across both Android and web platforms

Currently, I am developing a web version for my Android app. Within the app, there are numerous utility files such as a class that formats strings in a specific manner. I am wondering if there is a way to write this functionality once and use it on both ...

One typical approach in React/JavaScript for monitoring the runtime of every function within a program

Experimenting with different techniques such as performance.now() or new Date().getTime() has been done in order to monitor the processing time of every function/method. However, specifying these methods within each function for time calculation purposes h ...

The @Input directive is not compatible with the OnPush change detection strategy

page.html <app-parcel-delivery-cost-promo [parcelDeliveryCost]="parcelDeliveryCost"> </app-parcel-delivery-cost-promo> page.ts changeDetection: ChangeDetectionStrategy.OnPush, parcelDeliveryCost: Partial<ParcelDeliveryCostModel>; ...

Angular2 bootstrapping of multiple components

My query pertains to the following issue raised on Stack Overflow: Error when bootstrapping multiple angular2 modules In my index.html, I have included the code snippet below: <app-header>Loading header...</app-header> <app-root>L ...

Optimize your code in Angular 5 by consolidating or restructuring numerous Subscribe calls

Currently, I am utilizing Angular 5.2 for my web project. One of the pages includes multiple subscribe calls to various webAPI methods. While these calls are distinct and retrieve different datasets, I'm contemplating if there is a method to consolida ...

Issues with Ionic 3 Directive Not Functioning

Struggling to create a custom directive in Ionic that won't resize automatically? I can't figure out what's going wrong. Here's the code snippet from my project, which is an Ionic 3 app with Angular 4: import { Directive, HostListener ...

I'm trying to troubleshoot this issue - the duration is showing up as NaN years, NaN months, NaN weeks, NaN days, NaN

Currently I am troubleshooting an issue in my ionic project. I have a button and I want to display the date that the user selects. This is my code: age.component.ts import { Component, OnInit } from '@angular/core'; import * as moment from &apo ...

Ways to retrieve the name of the chosen option from a dropdown menu

Is there a way to retrieve the text name of a selected dropdown value using a PrimeNG dropdown? Incorporating a PrimeNG dropdown: HTML <p-dropdown [options]="regionSelectList" [(ngModel)]="reg" [filter]="true" [ngModelOptions]="{standalone: true}"> ...

``Using backticks to denote HTML syntax - Leveraging Google Charts to create

Has anyone found a way to incorporate HTML in ticks within a Google chart? I am attempting to insert a weather icon from This is my current attempt: const dailyData = new google.visualization.DataTable(); dailyData.addColumn('timeofday' ...