Selecting the checkbox to populate the input field

In my application, there is an input field that can be filled either by searching for an item or by clicking on a checkbox. When the user clicks on the checkbox, the input should be automatically filled with the default value valueText. How can I detect when the checkbox is selected and set the value to [ngModel].


 public foundedElement: Element[];
 public defaultValue: boolean;
 public valueText = "text";

 constructor(public elementFacade: ElementFacade) {}

 addField(value) {
    return currentElement.field = value;
 }

 searchElement(e): void {
    const {value} = e.target;
    if (value.length > 1) {
      this.elementFacade.getAll({name: value}).subscribe(el => this.foundedElement = el);
    }
  }
<input-container>
       <input #elementInput
              [mdAutocomplete]="autoElement"
              (input)="searchElement($event)"
              [ngModel]="currentElement ? currentElement.field : ''"
       />
       <md-autocomplete #autoElement="mdAutocomplete">
         <md-option
           *ngFor="let el of foundedElement"
           (onSelectionChange)="addField(el.name)">
           {{el.name}}
         </md-option>
       </md-autocomplete>
     </input-container>
     <md-checkbox  [checked]="defaultValue">Default</md-checkbox>

Answer №1

To achieve the desired functionality, you can implement the (change) event in the checkbox element so that when it is clicked, it updates the value of the input field accordingly:

<md-checkbox  [checked]="defaultValue" (change)="onCheckChange()">Default</md-checkbox>

In your TypeScript file, define the following function:

  onCheckChange() {
    this.inputValue = valueText;
  }

Here, this.inputValue represents the ngModel of the input field you wish to modify. If, for instance, the input field has a reference name of #elementInput, your function may look like this:

onCheckChange() {
    this.currentElement.field  = valueText;
  }

This approach will update the field once due to the nature of ngModel's declaration. To address this limitation, consider these two options:

  1. Utilize [(ngModel)] with an unmodified property.
  2. Employ (ngModelChange) to refresh the value of this.currentElement.field.

View a live demonstration here:

https://stackblitz.com/edit/angular-stack-checkbox-55528725?file=src/app/input/input.component.html

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

Using the map operator in an Angular 7 application with rxjs

Despite successfully compiling my code and having everything work perfectly, I encountered an error message in my IDE (Visual Studio Code) that is preventing me from deploying my app using ng build --prod: ERROR in src/app/training/training.service.ts(6 ...

Encountering a configuration error in the Nginx.conf file while attempting to use

I recently obtained a Visual Studio solution that includes multiple projects. https://i.sstatic.net/HuRyl.jpg A Nginx.conf file was created in ClientApp/Angular. https://i.sstatic.net/CN65e.jpg This is my docker-compose file: clientapp: image: ${DOCKER ...

The 'clientX' property is not recognized on the 'Event' type in Angular2 Directive

When attempting to retrieve the X position of my mouse in an Angular2 Directive using the following code: @HostListener('mousemove', ['$event']) onMousemove(event: Event): void { console.log(event.clientX) } I encountered an error ...

Error: The binding element titled implicitly possesses a type of 'any'

Encountering the following issue: ERROR in src/components/Header.tsx:6:18 TS7031: Binding element 'title' implicitly has an 'any' type. 4 | 5 | 6 | const Header = ({title}) => { | ^^^^^ 7 | return( 8 | ...

Choose a value, then multiply it by a number using a reactive

I have been attempting to multiply a fixed value by the selected value of a mat-select element, for example A x B, where A remains constant and does not change while B is the changing value from the mat-select. After performing this multiplication, I aim ...

Using Typescript with Gulp 4 and browser-sync is a powerful combination for front-end development

Could use some assistance with setting up my ts-project. Appreciate any help in advance. Have looked around for a solution in the gulpfile.ts but haven't found one yet. //- package.json { "name": "cdd", "version": "1.0.0", "description": "" ...

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: [ ...

"Optimize Your Data with PrimeNG's Table Filtering Feature

I'm currently working on implementing a filter table using PrimeNG, but I'm facing an issue with the JSON structure I receive, which has multiple nested levels. Here's an example: { "id": "123", "category": "nice", "place": { "ran ...

How to attach input to function invocation in Angular 2

Can we connect the @Input() property of a child component to a parent component's function call like this: <navigation [hasNextCategory]="hasNextCategory()" [hasPreviousCategory]="hasPreviousCategory()" (nextClicked)="next ...

Having difficulty installing node-sass in an Angular project

Having downloaded a repository from an existing Angular project, I proceeded to run sudo npm install within the project. While all packages were successfully installed, the node-sass package continued to cause issues. Upon completion of the installation ...

Error: The authentication state for auth0 is not valid

I'm currently working on integrating auth0 into my angular 5 application by following a tutorial found at: The registration process is functioning correctly, but I encounter an issue when attempting to log in. Upon logging in, the console displays th ...

Error encountered when retrieving data from Express using Angular service within Electron

Currently, I am facing a challenge with my Angular 4 app integrated within Electron and using express.js to fetch data from MongoDB. My dilemma lies in the communication process with express through http requests. Within my angular service, there is a met ...

There seems to be an issue with the request header field Authorization, as it is not permitted by the Access-Control-Allow-Headers in

My project involves using Angular 2 for the client side and Laravel 5.4 for the server side. I have set up APIs in Laravel and am making requests to them from Angular 2. In Laravel, I have configured Oauth 2 passport service to authenticate all APIs. For ...

Cookies with the HttpOnly attribute are not transmitted in a request

I have implemented the use of HttpOnly cookies in my Java code like this: ... Cookie accessTokenCookie = new Cookie("token", userToken); accessTokenCookie.setHttpOnly(true); accessTokenCookie.setSecure(true); accessTokenCookie.setPath("/"); response.addC ...

The intersection of conditional types and the combination of string literals with class unions

Encountered an unusual behavior in the types system when trying to type the as prop from emotion. import React, { Component, FC, PropsWithChildren } from "react"; // Defining possible types for `as` prop type AsType = | keyof JSX.IntrinsicElements | ...

Obtain canvas context within Angular from within a Web Worker

I am currently using platformWorkerAppDynamic to showcase my Angular application, but I am facing a challenge when trying to manipulate the canvas context. Though I can create a canvas using Renderer2, I am struggling to find a way to call the getContext(& ...

Verify the status of the nested reactive forms to determine if the child form is in a dirty state

I am working on a form that consists of multiple sections within nested form groups. I need to find a way to detect when changes are made in a specific section. Here is the HTML structure: <div [formGroup]="formGroup"> <div formGroupN ...

The issue encountered is: "Unable to assign property 'id' to a numeric value of '1' in Angular."

In my Angular 7 project, I am trying to establish a client-side request to the server-side. Below is the structure of the request that needs to be sent. { "title" : "Test Title", "user": { "id" : 7 ...

Changing the Value of an Input Element Dynamically in React: A Step-by-Step Guide

In a scenario where I have a component that takes an element, such as <input />, and I need to update its value programmatically after 15 seconds. Initially, I had the following approach in mind: const MyComponent = (myInput: JSX.Element) => { ...

Error message indicating unfulfilled peer dependency in Ionic Angular when using npm

Having trouble integrating the angular google maps package npm install @agm/core Encountering errors with unmet peer dependencies, unsure of the reason. Could it be that the version of Angular in my project is incompatible with the agm/core package? This ...