Obtain varied results from the Knockout module

In my application, I am utilizing Knockout and Typescript. One of the classes in my code is as follows:

class Address 
{
    State :string;
    ZIP: string;
    Street: string;
}

I want to create a component that will handle the updating of an object of this class.

Here's a snippet of my application:

var addressObservable = ko.observable(new Address() { State: "aaa", ZIP: "12211", Street: ""};

<address-component params="value: addressObservable"> </address-component>

The HTML and TypeScript VM for my component are as follows:

<div data-bind="with: address">
    <input data-bind="value: State" />
    <input data-bind="value: ZIP" />
    <input data-bind="value: Street" />
</div>

class AddressComponent<Brand> {
    public address: KnockoutObservable<Object>;

    constructor(params: AddressParams) {
        this.address = params.address;
    }
} 

In essence, a property in my application is passed to the component and bound to certain inputs within the component.

The main goal is for this component to assign a value to the "address" observable in one of two scenarios:

  1. "Address" object (if some properties are filled)

  2. null (if State, ZIP, and Street properties are empty).

I'm unable to convert the "address" object into ko.computed within the component. Similarly, I prefer not to modify it outside of the component. Does anyone have suggestions on how to achieve this?

Answer №1

By making the address properties observable, you can create a computed function that will return null if all properties are cleared:

function Address() {
  this.line1 = ko.observable("123 Main Street");
  this.line2 = ko.observable("");
  this.line3 = ko.observable("");
};

function App() {

  var address = new Address();
  
  this.displayAddress = ko.pureComputed(function() {
    if (address.line1() ||
        address.line2() ||
        address.line3()) {
      return address;    
    }
    
    return null;
  });
  
};

ko.applyBindings(new App());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<div data-bind="with: displayAddress">
  <p>Clear inputs to see address set to null</p>
  <input data-bind="value: line1">
  <input data-bind="value: line2">
  <input data-bind="value: line3">
</div>

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

Testing React Hook Form always returns false for the "isValid" property

When creating a registration modal screen, I encountered an issue with the isValid value when submitting the form. In my local environment (launched by npm start), the isValid value functions correctly without any issues. However, during unit testing us ...

What is the best approach for setting up a global pipe that can be utilized across various modules?

One of my Angular projects includes a custom pipe called CurrConvertPipe. import {Pipe, PipeTransform} from '@angular/core'; import {LocalStorageService} from './local-storage'; @Pipe({name: 'currConvert', pure: false}) expor ...

Setting up Jest to run in WebStorm for a Vue project with TypeScript can be done through

I am struggling to run all my tests within WebStorm. I set up a project with Babel, TypeScript, and Vue using vue-cli 3.0.0-rc3. My run configuration looks like this: https://i.stack.imgur.com/7H0x3.png Unfortunately, I encountered the following error: ...

The Next.js React framework seems to be having trouble reading user input from a

I'm encountering an issue when attempting to save form email/password registration using Next.js as it is throwing an error. import {useState} from 'react' type Props = { label: string placeholder?: string onChange: () => void na ...

Serving HTML from NodeJS instead of JSON

I have implemented two middleware functions import { NextFunction, Request, Response } from 'express'; const notFoundHandler = (req: Request, res: Response, next: NextFunction) => { const error = new Error(`Page Not Found - ${req.originalUr ...

The error message displayed by Create React App states: "You cannot utilize JSX without the '--jsx' flag."

I need help with overcoming this particular issue in a TypeScript based React application: Encountering an error stating "Cannot use JSX unless the '--jsx' flag is provided" ...

What is the best way to kickstart a Reactive Angular 2 form by utilizing an Observable?

My current strategy involves storing the form values in my ngrx store so that users can easily navigate around the site and return to the form if needed. The concept is to have the form values repopulate from the store using an observable. This is how I a ...

The 'Subscription' type does not contain the properties: source, operator, lift, subscribe, and three other properties that are present in the 'Observable<EnumValue[]>' type

Are you struggling with assigning an Observable<EnumValue[]> to another Observable<EnumValue[]>? fetchContactLocationStates() { this.contactLocationStates$ = this.enumValues$ .pipe(takeUntil(this.destroy$)) .subscribe(x => x.fil ...

Determine the data type of a property by referencing the data type of another property within an array of objects using TypeScript

I am working with a specific type of interface called Route that consists of name and path properties. interface Route { name: string, path: string } const routes = [ { name: "first", path: "/first" }, ...

The promise callback in Angular2 is unable to access this

This snippet of code is quite odd, but it resides within a service context: constructor() { gapi.load('client:auth2', this.loadGoogleApi); } private loadGoogleApi() { // Array of API discovery doc URLs for APIs used by the quickstart ...

What is the best way to ensure the website theme remains consistent after a refresh in React?

I am currently enhancing a weather forecast website by incorporating a theme toggler feature. The functionality has been successfully implemented, but I am facing an issue where the selected theme does not persist after reloading the page. Can someone he ...

Guide on exporting type definitions and utilizing them with npm link for a local package

I am in the process of developing a new testing tool called tepper as an alternative to supertest. My goal is to make this package available in both ESM and CJS formats. However, I'm encountering an issue where users of the library are unable to locat ...

Using computed properties with Nuxt's `head` property can result in error messages being displayed

While utilizing Nuxt.js, I am using head() { } method to configure SEO metadata. However, when accessing computed properties within this method, Vetur displays the following message: Property 'domain' does not exist on type 'CombinedVueInst ...

Applying Validators manually in Angular 2 beta 17

We are currently working on a legacy project that needs to be maintained until the final version with angular-final is deployed. Once we upgrade to the final version, I will be able to easily apply conditional Validators using: this.myForm.controls[&apos ...

Trouble viewing Three.js content in Index.html

My current project involves building a website using three.js with typescript. However, I am facing an issue where only the header from my index.html file is displayed when I try to load the website onto a local server. The main problem arises when I atte ...

Managing state on the login page functions properly, although there is a minor inconvenience of having to click the login button twice after entering the username and password

In Login.tsx, I store user/pass info in a useState called login and pass it up to App.tsx. I then store the access property from login useState to access useState inside App.tsx. While this does technically work, there is an issue where it seems to be one ...

Angular's change detection is currently inactive

I need to toggle the visibility of a button based on the value of a boolean variable using the Output property. However, I am facing an issue where the button remains hidden even after the variable is updated with a true value. Parent Component.ts showE ...

Tips for resolving the TypeScript error related to the global object in Node.js

I am currently working on a project following the steps outlined in this guide https://vercel.com/guides/nextjs-prisma-postgres to develop a full stack application. However, I have encountered an error with TypeScript in the code snippet below: import { Pr ...

I am experiencing difficulties in assigning values to a formArray

I am struggling to update values in an array form, as I am facing challenges setting new values. Although I attempted to set values using patch value, my attempts were unsuccessful. // Component.ts this.packageForm = this.formBuilder.group({ title: [&a ...

Is it possible to add additional text to an input field without modifying its existing value?

I have a numerical input field labeled "days" that I want to add the text " days" to without altering the actual numerical value displayed. <input type="number" class="days" (keyup)="valueChanged($event)"/> Users should only be able to edit the num ...