Obtain the Angular 2 Form object within a TypeScript class file for manual configuration of form properties

I have a form inside a PrimeNG dialog control. I need to handle two different submit methods based on certain conditions for this form, so I don't want to use the ngSubmit method in the form tag. Instead, I want to manually access the form object in my TypeScript class file to set its "submitted" or "valid" properties and make decisions based on that. How can I achieve this? Essentially, how do I gain control over the form in my class file to manipulate its internal properties?

HTML:

<p-dialog header="Create New Message" [(visible)]="IsShowNewMessageDialog"
      modal="modal" width="800" height="auto" styleClass="modal-blue" appendTo="body">
<form #f="ngForm" name="newMessageForm" (ngSubmit)="f.form.valid" novalidate autocomplete="off">
    <div *ngIf="model && IsShowNewMessageDialog">
        <div class="ui-g">
            <div class="ui-g-11">
                <span style="color:red">{{ErrorMessage}}</span>
            </div>
        </div>

        <div class="ui-g">
            <div class="ui-g-2"><label class="">To</label></div>
            <div class="ui-g-10" [ngClass]="{ 'has-error':  f.submitted && !emailTo.valid }">
                <input type="text" [(ngModel)]="model.emailTo" #emailTo="ngModel"
                       class="text-field"
                       pInputText name="emailTo"
                       placeholder="Email To *" minlength="3"
                       required>
            </div>
        </div>

        <div class="ui-g">
            <div class="ui-g-2"><label class="">CC</label></div>
            <div class="ui-g-10">

                <input type="text" [(ngModel)]="model.cC" #CC="ngModel"
                       class="text-field"
                       pInputText name="CC"
                       placeholder="CC" minlength="3">
            </div>
        </div>

        <div class="ui-g">
            <div class="ui-g-2"><label class="">Bcc</label></div>
            <div class="ui-g-10">

                <input type="text" [(ngModel)]="model.bcc" #BCC="ngModel"
                       class="text-field"
                       pInputText name="BCC"
                       placeholder="BCC" minlength="3">
            </div>
        </div>

        <div class="ui-g">
            <div class="ui-g-2"><label class="">Subject</label></div>
            <div class="ui-g-10" [ngClass]="{ 'has-error': f.submitted && !subject.valid }">
                <input type="text" [(ngModel)]="model.subject" #subject="ngModel"
                       class="text-field"
                       pInputText name="subject"
                       placeholder="Subject *" minlength="3"
                       required>
            </div>
        </div>

        <div class="ui-g">
            <div class="ui-g-12">
                <p-editor name="emailBodyPlain" #emailBodyPlain="ngModel" [(ngModel)]="model.emailBodyPlain"
                          placeholder="Email Body *" [style]="{'height':'320px'}"
                          minlength="3"></p-editor>

            </div>
        </div>

    </div>

    <div class="text-right pr-5">
        <button class="btn btn-warning" type="button"
                [disabled]="!f.form.valid"
                (click)="sendNewMail(false)" label="Send">
            <i class="fa fa-paper-plane"></i>&nbsp;Send
        </button>
        <button class="btn btn-warning" type="button"
                [disabled]="!f.form.valid"
                (click)="saveNewMail(true)" label="Save">
            <i class="fa fa-floppy-o"></i>&nbsp;Save
        </button>
    </div>
</form>
</p-dialog>

Submit Method:

saveNewMail(isDraft) {
    this.messageCenterService.saveNewMail(this.newMail)
        .subscribe(
        data => {
            this.IsShowNewMessageDialog = false;
        },
        error => {
            this.ErrorMessage = error.Message;
        });
}

Answer №1

Instead of using ng-submit, consider utilizing the (click) event on the submit button to pass form values to the component as shown in the example below:

<button (click)="onSubmit(newMessageForm.value)"></button>

In the component, define an onSubmit method with a parameter that will contain the form value. Additionally, you can disable a button based on form validity using the following syntax:

<button [disabled]="newMessageForm.invalid"></button>

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 present {object object} within a table format?

I'm hoping to showcase this information in a table format. The data currently appears as {object object}. My goal is to extract and display the "last," "buy," and "sell" values for all currencies without hard coding it. I believe using ng-repeat or ng ...

The most efficient method for distributing code between TypeScript, nodejs, and JavaScript

I am looking to create a mono repository that includes the following elements: shared: a collection of TypeScript classes that are universally applicable WebClient: a react web application in JavaScript (which requires utilizing code from the shared folde ...

Using TypeScript to access the outer "this" from a literal getter

When attempting to access the outer "this" scope in Typescript while using getters and setters in object literals, it seems there is no straightforward method. Take for example the code snippet below: class Report { stuff: any[]; options = { ...

Encountering NodeJS server issues with 505/404 errors while fetching partials

I am currently working on an application built using the M.E.A.N stack. For routing, I have implemented Angular Ui Router. However, I am encountering difficulties in correctly routing partials. The link for the main view is functioning properly with the ...

Implementing Event Handlers Post-Infinite Scroll Refresh

I have incorporated the infinite scroll feature using a plugin that can be found at this website. This plugin helps in loading page content seamlessly. One jQuery event listener that I have set up is as follows: $('.like-action').on('click ...

Compare two lists in Angular 4 and verify all the elements that are common in both

Two lists are in my possession roles{admin, guest, configuration manager}(contains all roles of the system) loggedInUserRoles {admin , guest}(holds the roles of the currently logged in user) Within a user edit form, there is a checkbox for each user. M ...

What is the best method for obtaining a spring controller's object using AJAX?

Here is the AJAX call I am working with: var url = "UsersGroupReader.html?selectedCompanyName=" + selectedCompanyName + "&test="+Math.random(); req.onreadystatechange = processAccessGroupRequest; req.open("GET", url, true); req.send(null); function ...

Tips for preventing hcaptcha from displaying image challenges during web scraping with puppeteer

When I attempt to scrape a website, the process of passing the captcha can be unpredictable. Sometimes, after clicking on the captcha checkmark, I am presented with images to solve the captcha. Other times, it simply passes me through without any further a ...

Troubleshooting: AngularJS ng-include not functioning as expected

I attempted to replicate the steps outlined in an Angular template at . Unfortunately, something went wrong and I am unable to identify the issue. Here is what the code looks like: menu.html <div class="container"> <div class="row row-conte ...

"DataTransfer object in IE 10 does not contain any information when using drag and drop

I am struggling with my drag and drop upload code in IE 10. The event handlers in my code are as follows: dragCatcher.on('drop', function (e) { e.preventDefault(); e.stopPropagation(); console.log(e.originalEvent.dataTransfer.files); }).on ...

I seem to be encountering an issue while looping through an array of objects. Instead of retrieving all two elements, only one object is being returned. Can

Just a heads up, I'm new to coding so please bear with me. I'm attempting to run through the "diary" array and the function "howMany" is only showing 2 'Home' elements, although there are actually 4 'Home' elements in total i ...

Initiate a fresh start with an automatic input reset

When you perform an action in the first id = "benodigheden", I believe there should be a specific outcome that then triggers a second rule for id = "benodigheden". However, I have been unsuccessful in finding information on this topic online. It seems like ...

Error: Unable to access property 'BOTTOM' of an object that is not defined

Hi there, I'm having trouble with this error. Can you assist me? [ERROR] TiExceptionHandler: (main) [340,3234] /ui/common/ApplicationTabGroup_Andr.js:1703 [ERROR] TiExceptionHandler: MainWallTable.insertRowBefore([0, PendingUploadView, T ...

Trapping an anchor tag event in asp.net

I am currently working on a menu bar using HTML code (I am unable to use asp link buttons). <ul> <li><a href="#"><span>Reconciliation</span></a> <ul> ...

Is there an efficient method for matching "data-" attributes with property names in mixed case?

In my custom jQuery plugins, I utilize a base plugin class that goes beyond what the jQuery UI widget offers by handling more complex tasks. Currently, I am looking to extract values from data- attributes attached to elements and incorporate them as optio ...

Vue form component triggers the submit event twice

In my current project, I am utilizing the most recent version of Vue 3 without any additional vendors. After experiencing a setback in which I invested several hours attempting to uncover why my form component was triggering the submit event twice, I am le ...

The Primeng Angular2 checkbox malfunctioning issue

My form setup in Angular2 CLI looks like this: Inside the component export class UsersAddComponent implements OnInit { ngOnInit() { this.userForm = this._formBuilder.group({ role: ['', [Validators.required]], others: this._for ...

What is the best way to persist my data on a page when I navigate to a different page in React.js?

Currently, I am utilizing Material UI tabs with 8 pages as components. Each page contains input areas, and when I switch between tabs, the data in the inputs gets cleared. I want to retain this data even when moving to another tab. How can I achieve this ...

Examining if elements in a mapped array have common values

Currently, I am working on creating a news feed with React and moment.js. By utilizing the .map method, I am able to display items with titles and content. My goal is to determine if an item was published in the same year and month as another item. In such ...

The proper way to close file descriptors on a terminated HTTP connection in a Node.js environment

I am currently experimenting with Node.js, where I am attempting to stream files from the filesystem over HTTP. However, my experience on an OS X Lion machine has been hindered by a buggy Apache Bench (ab) app that prematurely aborts connections. This issu ...