send the checkbox control's model value back to the parent control in Vue3

I've implemented a wrapper control for checkboxes that closely resembles my textbox control. This approach ensures consistent validation and design throughout the application. While I was successful in getting it to work for textboxes, I encountered some challenges with the boolean value for the "checked" property.

Two way binding of data between child and parent using emit vue3 typescript

<template>
  <label class="checkCtrl">
    <input
      role="checkbox"
      aria-disabled="false"
      aria-readonly="false"
      type="checkbox"
      v-model="checked"
      v-on:change="change($event)"
    />
    <span><LocCtrl :page="page" :loc-key="labelLoc" /></span>
  </label>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { useModelWrapper } from "../utils/modelWrapper";
import LocCtrl from "../components/LocCtrl.vue";
import Locale from "@/services/Locale";

export default defineComponent({
  name: "CheckCtrl",
  components: {
    LocCtrl,
  },
  props: {
    labelLoc: {
      type: String,
      required: true,
    },
    modelValue: {
      type: String,
      required: true,
    },
    page: {
      type: String,
      required: true,
    }
  },
  setup(props, { emit }) {

    const value = useModelWrapper(props, emit, "value");
    return {
      value: value,
      checked: value.value == "true"
    }
  },
  methods: {
    getLoc(locKey: string): string {
      return Locale.getItem(this.page, locKey);
    },
    change(e: Event): void {
     if (e) {
        this.value = (e.target as HTMLInputElement).checked ? "true" : "false";
        this.$emit('update:modelValue',  this.value);
        alert(this.value);
      }
    }
  },
});
</script>

This is the model wrapper that worked for textboxes but ran into issues with checkboxes

import { computed } from "vue";
export function useModelWrapper(
  props: { [x: string]: any },
  emit: (arg0: string, arg1: any) => void,
  name = "modelValue"
) {
 return computed({
    get: () => {
      return props[name];
    },
    set: (value: string) => {
      return emit("update:" + name, value)
    }
  });
}

In the parent component, I'm passing the v-model to the checkbox control. The expected values are strings "true" or "false" (which can be easily configurable if needed).

<FormLine className="forCheck" form-line="3">
    <CheckCtrl v-model="claim.resultOfAccident" labelLoc="RoA" page="claims3View"/>
</FormLine>

Answer №1

Once again, I managed to find a solution to my problem on my own. Hopefully, this code snippet can be beneficial to others:

onChange(event: Event): void {
   if (event) {
      const result = (event.target as HTMLInputElement).checked ? "true" : "false";
      this.$emit('update:modelValue', result);
   }
}

The initial issue with 'this.value' has now been resolved.

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

Why does the inferred type not get resolved in the else block of the ternary operator when using infer on a generic type?

Consider a scenario where we have a type with a generic argument T: type Wrap<T> = { data: T }; If we define another type to extract the generic T: type Unwrap<W> = W extends Wrap<infer T> ? T : T; Why does using T in the else clause ...

Typescript interface designed for objects containing certain optional property names as well as unspecified property names

I am looking to design an interface for an object that can have optional properties with specific names, as well as accept properties with arbitrary names. Here is my approach: interface CallBack { onTransition?(): any; // option A [key: string]: () = ...

Validating object values prior to adding a key

How can we add a new key-value pair called partnerCam to the res.items objects when partnerTermStart and partnerTermEnd are not null? If partnerTermStart and partnerTermEnd have values, then we should insert a new key called partnerCam with a value calcul ...

Shift the Kid Element to an Alternate Holder

Currently, I am working on a project in Angular version 10. Within this app, there is a component that can be shared and will utilize the provided content through ng-content. Typically, this content will consist of a list of items such as divs or buttons. ...

ESLint version 8.0.0 encountered an error while attempting to fetch the '@typescript-eslint' plugin

Hey there, I'm in need of some assistance. I encountered an error while trying to build a project. Uh-oh! Something didn't go as planned! :( ESLint: 8.0.0 TypeError: Failed to load plugin '@typescript-eslint' specified in ' ...

Disruptions in typing occur due to errors popping up while utilizing zod and react-hook-forms within a TypeScript application

Currently, I am working on developing a registration page for users using react-hook-forms for the registration form and zod for validation. Initially, when testing the form, I noticed that errors only appeared after submitting the form. However, once the ...

Array[object..] logical operators

I am currently working with Boolean and logical operators using code like this: Just so you know, I want to convert object values and logic into an array to perform logical operations. For example: object1.logic object.operators object2.logic as either tr ...

Higher-Order Component integrated with HTMLElement

Check out this complex code snippet I created: export type AdvancedHoverElementProps<TElement extends HTMLElement> = React.HTMLProps<TElement> & { hoverDuration: number, onHoverChanged: (isHovering: boolean) => void }; export ...

The absence of essential DOM types in a TypeScript project is causing issues

Recently, I've been working on setting up a web app in TypeScript but I seem to be missing some essential types that are required. Every time I compile using npm run build, it keeps throwing errors like: Error TS2304: Cannot find name 'HTMLEleme ...

Incorporate a JavaScript library into a personalized JavaScript file that is utilized within my Angular2 project

Integrating Machine Learning into my Angular2 project using the "synaptic.js" JavaScript library is my goal. After executing the command npm install synaptic --save I intend to execute a custom javascript file (myJsFile.js): function myFunction() { v ...

Tips on deactivating a div when a checkbox is selected

I am currently working with a checkbox element in my code: <md-checkbox checked.bind="addEventCommand.allDay" change.delegate="allday()">All Day</md-checkbox> When the above checkbox is true, I want to disable the following ...

Encountering an issue accessing a property retrieved from a fetch request in TypeScript

I am currently dealing with the property success defined in the API (reCAPTCHA). /** * The structure of response from the veirfy API is * { * "success": true|false, * "challenge_ts": timestamp, // timestamp of the challen ...

Excluding the decimal point from version 1.0 in an API response with Angular 5

When working with Angular 5, I encountered an issue where the API response was returned as 1.0, but when displayed in the HTML field it only showed as 1. Upon inspecting the response in Chrome dev-tools, under the Network tab -> Response, it correctly ...

When attempting to parse a file name using a regular expression in TypeScript (or even plain Node.js), the unexpected outcome is a

Looking to extract language information from a filename? Check out this simple construct: The structure of my language.ts model is as follows: export interface Language { language?: string; region?: string; } The function designed for parsing the fi ...

I possess both a minimum and maximum number; how can I effectively create an array containing n random numbers within

Given a minimum number of 10.5 and a maximum number of 29.75, the task is to generate an array within these two ranges with a specific length denoted by 'n'. While the function for generating the array is provided below, it is important to calcul ...

SolidJS directives utilizing use:___ result in TypeScript errors when used in JSX

As I work on converting the forms example from JS to TS, I came across a typescript error related to directives in HTML: https://i.sstatic.net/Hl8Pv.png It appears that validate and formSubmit are being recognized as unused variables by typescript, result ...

Setting a TypeScript version in Atom: Step-by-step guide

I'm currently grappling with using a specific version of TypeScript in Atom. For an older project that relies on Backbone, the latest TypeScript version doesn't compile properly, so I need to use an earlier one. The closest solution I've co ...

When changing the dropdown option on a separate page in React/Next JS, all checkboxes show the clicked style as a result of utilizing useState

I have implemented checkboxes for three different categories: "Types", "Price", and "Categories". They function correctly, with data being passed to a separate checkbox component without any issues. The problem arises when I click a checkbox and then inte ...

Updating the node startup file with Visual Studio 2015 using NodeJS/Typescript

Encountering a persistent error: Error Code: TS5055 Cannot write file C:/project/dir/server.js' because it would overwrite the input file. Project: TypeScript/JavaScript Virtual Projects Even after renaming my entry filename to nodeserver.js, the ...

I'm currently working on creating an online store using Next.js and TypeScript, but I'm struggling to effectively incorporate my fake product data array into the site

"using client" import Container from "@/components/Container"; import ProductDetails from "./ProductDetails"; import ListRating from "./ListRating"; import { products } from "@/utils/products"; interface I ...