Ways to specify a setter for a current object property in JavaScript

Looking to define a setter for an existing object property in JavaScript ES6? Currently, the value is directly assigned as true, but I'm interested in achieving the same using a setter.

Here's a snippet of HTML:

<form #Form="ngForm" novalidate (ngSubmit)="saveForm()">
<label class="radio-inline pr-3">
<input type="radio" name="isCitizen" required value="yes [(ngModel)]="formList.isCitizen" #isCitizen="ngModel"> Yes
</label>
<label class="radio-inline">
<input type="radio" name="isCitizen" required value="no"[(ngModel)]="formList.isCitizen"#isCitizen="ngModel"> No
</label>
<form>

And here's a piece of the component code:

 import { Component } from '@angular/core';

 @Component({
 selector: 'my-app',
 templateUrl: './app.component.html',
 styleUrls: [ './app.component.css' ]
 })
 export class AppComponent  {
 name = 'Angular';
 formList: FormModel = new FormModel();

 saveForm(){ //how to set the value to object using setter
 if(this.formList.isCitizen === 'yes'){
 this.formList.isCitizen = true;
 }else{
 this.formList.isCitizen = false;
 }
 }
 }

 export class FormModel {
 isCitizen : boolean;
 }

Check out a demo

Answer №1

If you're working with TypeScript, consider the following:

export class UserForm {
    private  _isMember : boolean;

    set isMember(isMember:boolean) {
        this._isMember = isMember;
    }
    get isMember():boolean {
       return this._isMember ;
    }
}

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

A common inquiry: how can one pinpoint a location within an irregular figure?

I have been studying Html5 Canvas for a few weeks now, and the challenge mentioned above has puzzled me for quite some time. An irregular shape could be a circle, rectangle, ellipse, polygon, or a path constructed by various lines and bezier curves... I ...

Frontend update: Changing the display format for dates

Received from the backend is an array of objects (leavedays)- var leavedays = [{"_id":"62d544ae9f22d","season":2022,"name":"LEAVEDAY1","dateFrom":"2022- 07-26T00:00:00.000Z","date ...

Transforming Observable into a Promise

Is it considered a best practice to convert an observable object to a promise, given that observables can be used in most scenarios instead of promises? I recently started learning Angular and came across the following code snippet in a new project using ...

React router loader is not functioning correctly when trying to fetch data

My attempt to fetch an array of data from an API is resulting in an empty response within the application. However, when I try the same call in a swagger, it returns the correct array. HomePage.tsx: const HomePage = () => { const books = useLoaderDat ...

How to dynamically disable options in a Vuetify v-select based on the type of object value

When utilizing the Vuetify v-select component and setting the prop multiple, we can select multiple values at once. In this scenario, I have a variety of recipes categorized under Breakfast or Dinner using the parameter type. The goal is to deactivate al ...

Dynamic Angular select options with ngFor causing cascading changes in subsequent selects

In my Angular 5 project, I am attempting to create a set of three <select> elements using *ngFor. I came across a helpful thread on Stack Overflow that provided some guidance (check it out here). However, I've encountered an issue where the sele ...

Oops! Issue: The mat-form-field is missing a MatFormFieldControl when referencing the API guide

I included the MatFormFieldModule in my code like so: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; ...

Retrieve elements within an element using its reference

<div ref={location} className={style.locations}> {locations.map(loc => ( <span onClick={onClick}> {loc.name} </span> ))} </div> My goal is to manipulate the <span> elements w ...

Trouble with rendering inline images from markdown files in GatsbyJS

I've been trying to include inline images in my markdown file with the gatsby-remark-images plugin. However, I'm facing an issue where the image is not loading on my local host. I'm not sure if it's a syntax error or if I'm missing ...

When I tried to retrieve the value by using deferred.resolve(value) in my .then() method, it

I am currently utilizing Q.js to make an API call with two loops in my main function structured like this: for i..10 for i...5 var promise = getLoc(x,y); promise.then(function(value) { //value is undefined... ...

Error: The selected module is not a valid top-level option

I am facing an issue while using the babel-loader. I have removed all irrelevant code and just kept the error-related portion. What could be causing this problem? module.exports = merge(baseWebpackConfig, { ... module: { rules: [ ...

Creating an external link in Angular with query parameters

I have created an app where users have their addresses listed, and I want to implement a feature that allows me to open Google Maps when clicking on the address. However, I am currently facing an issue where instead of getting the actual value of {{ this. ...

Tips on resolving the Warning message: "The event handler property `onExited` is a known property in StatusSnackbar component, but it will

When using the StatusSnackbar component, I encountered a warning about a known event handler property onExited. How can I resolve this issue? Component: import Snackbar from '@material-ui/core/Snackbar' import { withStyles } from '@material ...

Tips for restricting users from inputting spaces into a form field using ReactJS

Within my application, I have developed a specialized component named QueryForm that serves the purpose of enabling search capabilities. The code snippet being outputted by this component is as follows: ...

How to convert form fields into JSON format using Angular 2

Currently, I am in the process of learning angular2 and have encountered a roadblock. I have created a form where the values are populated through JSON. The form consists of both pre-filled fields and text input fields where users can enter data and select ...

Displaying a JQuery loading image on a webpage for a designated amount of time

I am trying to display an image in a div once a price calculation function is called. The image should cover the whole page. Can someone assist me with this? <div class="Progress_Layout" style="display:none"> <div class="Progress_Content"> ...

Guide to creating a nested list using the jQuery :header selector

Here is the structure of my html: <h1 id="header1">H1</h1> <p>Lorem ipsum</p> <h2 id="header2">H2</h2> <p>lorem ipsum</p> <h2 id="header3">H2</h2> <p>lorem upsum</p ...

Uncover hidden content by clicking a button with JavaScript

I need help with creating a function that hides additional content until a button is clicked. Currently, my script displays the content by default. How can I modify it to hide the content by default and only reveal it when the button is clicked? functi ...

What is the best way to add attachments to the clipboard in a Chrome extension?

One possible way to achieve this is by using the navigator.clipboard.write API, but keep in mind that this API is not available to background pages of Chrome extensions. A method I attempted involved creating a blob like this: let blobFinal = null; // ...

Determine whether a subdomain is present within an ajax file in php

Looking for assistance with checking the existence of a 'Subdomain' in a file called '\example\sites'. Here's the code: $form = array() ; $form['name'] = "install"; $form['action'] = "?step=2"; $for ...