``Incorporating event and parameter as arguments for a function in an Angular application: a tutorial

I am trying to incorporate a checkbox in Angular where if it is enabled, the event.target.checked value is true, and if it is disabled, the event.target.checked value is false. When clicking the checkbox, I need to call a function where I want to pass the event and value. I am not sure if passing event and values as arguments is possible in Angular or not?

XYZ.component.html

<form [formGroup]="XYZGroup">
        <div class="form-group row">
            <div class="col-md-4 text-left" id="email">
                <label><input type="checkbox" formcontrolName="emailData" [checked]="Data.email=='enabled'" (change)="checkEmail($event.target.checked, value)">&nbsp;
                    <b>Email</b></label>
            </div>
        </div>
<form>
<button (click)="submit()">Submit</button>

XYZ.component.ts

ngOnInit(){
 this.XYZGroup = this.fb.group({
      emailData: new FormControl(''),)}
}

checkEmail(e, value) {
    if (e) {
      value = "enabled"
    }
    else {
      value = 'disabled'
    }
    return value;
  }

submit(){
let emailDataValue = this.checkEmail(event, this.XYZform.value.emailData)
body:{
"email": this.emailDataValue
}
}

My question is if 'this.XYZform.value.emailData = disabled' means I need to uncheck the checkbox, and if 'this.XYZform.value.emailData = enabled' means I need to check the checkbox

Answer №1

@Component({
    selector: 'unique-selector-name',
    template: `
        <form [formGroup]="theForm" (submit)="saveForm()">
                    <label><input type="checkbox" formcontrolName="email" >Enabled</label>
                    <button type="submit">Submit</button>
        <form>
    `
})

export class UniqueComponent implements OnInit {
    theForm: FormGroup;
    constructor(private fb: FormBuilder) {
        this.theForm = fb.group({
            email: false
        })
    }
    
    ngOnInit() { }

    saveForm(){
        let formValues = this.theForm.getRawValue();
        let body = {
            email: formValues.email ? 'enabled': 'disabled';
        }

    }
}

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

Typescript causing issues with Material-UI theme.mixins.toolbar functionality

Currently, I am utilizing Material-UI to develop a React and Typescript website. The experience has been positive overall, but I am facing a specific issue. I have been trying to implement one of the code examples from their documentation, but unfortunatel ...

Display the inputs from a reactive form in a different component

I am currently facing a situation where I have multiple components, such as component A, containing a reactive form. The data from these forms is stored in a central service. My goal now is to display a preview of this form in component B. However, upon na ...

"Error: The method setValue is not found in the AbstractControl type" when trying to clear form in Angular 2

Here is the template code: <form [formGroup]="form" (ngSubmit)="onSubmit(form.value)" novalidate="novalidate"> <textarea [ngClass]="{ 'error': comment }" [formControl]="form.controls['comment']" ...

What is the best approach for initializing and adding dataset in a database using Nest.JS when launching the application for the first time?

In managing my database, I have multiple tables that require default information such as categories, permissions, roles, and tags. It is crucial for me to ensure that this exact information has consistent IDs whenever the application is freshly launched on ...

Strategies for Implementing Pagination in an Angular 2 HTML Table Without the Use of Third-Party Tools

I have an HTML table that displays basic details along with images. I am looking to implement pagination for this table in Angular 2. Are there any alternatives to using ng2-pagination? ...

Guidance on transferring information from a parent component to an Angular Material table child component

Currently, I am implementing an angular material table with sorting functionality. You can view the example here: Table Sorting Example I intend to transform this into a reusable component so that in the parent component, all I have to do is pass the colu ...

When trying to convert a jest test to typescript, an error message may be encountered stating: "SyntaxError: Unable to

As I delved into the clear and concise jest documentation, I managed to successfully implement this test: const { spawnSync } = require('child_process'); const ls = spawnSync('ls', ['-lh', '/usr']); const unexistent ...

Angular 2 chart showing horizontal stacking of databars

I am in search of a chart that visually represents different percentages. The purple bar should represent around 40%, the darkest blue approximately 10%, and the green about 8% of the total. After some research, I have come across this as a similar option, ...

Upon refreshing the page, the Vuex store getter displays [__ob__: Observer]

After each page refresh, my Vuex store getter returns [__ob__: Observer]. The version of Vue being used is 2.2.3 along with TypeScript. Initially, the data loads correctly from an external API, but when utilizing the getter, it fails and requires another ...

How to Restrict the Use of Conditional "If" Statements in Another Function in Angular 7

How can I use an IF condition inside a function to only execute once for a specific action and not for another action? I have a function that is called twice, but I want the first "IF" condition inside the function to only be triggered when the add bank b ...

Angularfire2 with Firebase - receiving notifications for added child in queried list

Is it possible to utilize the "child_added" event with queried lists? For example: this.curUserPosts = this.af.database.list('/posts', { query: { orderByChild: 'user/id', equalTo: id } }).$ref.on("child_added", (c ...

Using Typescript: invoking static functions within a constructor

This is an illustration of my class containing the relevant methods. class Example { constructor(info) { // calling validateInfo(info) } static validateInfo(info):void { // validation of info } I aim to invoke validateInfo ...

Deactivate the Mention and Hash tag in ngx-linkifyjs

I am currently utilizing ngx-linkifyjs to automatically convert URLs in text to clickable hyperlinks. However, I am facing an issue where it is also converting # and @ tags into links. Is there a way to prevent the conversion of # and @ while maintain ...

Encountering an "Unexpected token" error when importing a JSON file in TypeScript even though the JSON is valid

I recently read an article on Hacker Noon about importing JSON into TypeScript, and decided to give it a try in my code. Here's the import line I used: import data from './assets/fonts/helvetiker_bold.typeface.json'; To test if the import ...

How can I bind Angular to the selection of a file input field?

I am facing an issue with my upload form where the displayed filename is showing a virtual filepath instead of just the filename itself. How can I improve the binding to only display the filename (like selected.files[0].name) without any virtual path? My ...

Discovering a variable within an enzyme wrapper for the locate function

Struggling through testing with jest + enzyme. I have an array called OptionsArray that contains options mapped to buttons in a component. In my testing suite for the component, I attempted to do the following: import React from 'react'; import { ...

Enhance your website with unique and custom fonts using

I am utilizing this repository. How can I incorporate custom fonts into my project? I have created a folder named "fonts" within the assets directory and placed my fonts there. fonts.scss @font-face { font-family: 'Lato'; src: url('../ ...

Troubleshooting asynchronous problems with rxjs chaining within ngrx effects

@Effect({ dispatch: false }) public setJwtDataParcoursPage = this.actions$.pipe( ofType(INIT_FORM_SUCCESS_ACTION), map((action: InitFormSuccessAction) => action.payload), withLatestFrom(this.store.select(this._apiHeadersSelector.getJwt) as Observa ...

What is the recommended approach for sending a null value to a mandatory property in a Vue.js component?

Setup: Vue.js (3.2) with Composition API, TypeScript, and Visual Studio Code File type.ts: export class GeographicCoordinate { latitude: number; longitude: number; altitude?: number; constructor(latitude: number, longitude: number, altitude?: num ...

Unable to access or modify NGXS state within an Angular 8 NativeScript application

After gaining experience with Angular, I decided to experiment with the NGXS data store while following a NativeScript tutorial. Despite trying several NGXS tutorials, I couldn't get the state to update without any errors from Android Studio or NS. N ...