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

Firestore TimeStamp.fromDate is not based on UTC timing

Does anyone have a solution for persisting UTC Timestamps in Firestore? In my Angular application, when I convert today's date to a Timestamp using the code below, it stores as UTC+2 (due to summer time in Switzerland). import {firebase} from ' ...

Description: TypeScript type that derives from the third constructor parameter of a generic function

How can I determine the type of constructor props for a generic type? Take a look at this example. type PatchableProps<T> = T extends { [k: string | number]: any } ? { [Key in keyof T]: PatchableProps<T[Key]> } : T | Patch export class ...

Show a notification pop-up when a observable encounters an error in an IONIC 3 app connected to an ASP.NET

Currently, I am in the process of developing an IONIC 3 application that consumes Asp.NET web API services. For authentication purposes, I have implemented Token based auth. When a user enters valid credentials, they receive a token which is then stored in ...

Managing conflicting versions of React in a component library created with Webpack and Storybook

My goal is to create a React component library on top of MUI using Storybook and TypeScript. Since Storybook is based on Webpack (which includes SASS files), I'm utilizing Webpack to build the bundle because TSC can't compile those files. Subsequ ...

Learn how to display or conceal the HTML for 'Share this' buttons on specific routes defined in the index.html file

Currently, I am in the process of updating an existing Angular application. One of the requirements is to hide the "Share this buttons" on specific routes within the application. The "Share" module typically appears on the left side of the browser window a ...

Visual Studio Code unable to locate source maps for typescript debugging

Looking for some help debugging a basic Hello World TypeScript file. Whenever I try to set a breakpoint, it seems like VS Code is having trouble locating the source map, even though it's saved in the same directory. I'm using Chrome as my browser ...

Issue with react-router-dom loader defer type issue

I attempted to troubleshoot the issue with data loading by incorporating defer in the loader function. I am unsure how to specify the postResponse type, which represents the actual response data. Even after experimenting with type casting and other m ...

Seems like ngAfterViewInit isn't functioning properly, could it be an error on my end

After implementing my ngAfterViewInit function, I noticed that it is not behaving as expected. I have a hunch that something important may be missing in my code. ngOnInit() { this.dataService.getUsers().subscribe((users) => {this.users = users) ; ...

The module 'MatTableModule' could not be located within the '@angular/cdk/table' package during export

Having an issue with using where I'm getting the error message "export 'MatTableModule' was not found in '@angular/cdk/table'. Not sure what I might be doing wrong? You can find more details in my GitHub repository: https://githu ...

Count duplicated values in an array of objects using JavaScript ES6

I am working on creating a filter for my list of products to count all producers and display them as follows: Apple (3) I have managed to eliminate duplicates from the array: ["Apple", "Apple", "Apple"] using this helpful link: Get all non-unique values ...

Displaying Data in a Tree Structure Using JSON

I am currently working on an Angular project which includes a nested JSON file structured as follows: I would like to import this JSON data from the file and create a treeview populated with its contents. How can I achieve this? { "?xml": { ...

How to prevent unnecessary new instances from being created by the Inject() function in Angular

Can someone please clarify if the inject() function provides different instances of a service? I suspect this might be why my code is not functioning as expected. Let's examine the code snippet below: { path: 'recipes', comp ...

Result from Nativescript ModalView

crongoramaModal() { let options = { context: {}, fullscreen: true, viewContainerRef: this.viewRef }; this.modalService.showModal(CronogramaManejoComponent, options) .then((result: CronogramaManejo)=>{ ...

Struggling with setting up Angular Material and SCSS configuration in my application -

Hey there, I encountered an error or warning while trying to launch my angular app. Here's the issue: ERROR in ./src/styles/styles.scss (./node_modules/@angular-devkit/build- angular/src/angular-cli-files/plugins/raw-css- loader.js!./n ...

The error message "Cannot bind to 'matDatepicker' because it is not recognized as a property of 'input'" is indicating an issue with Angular

After copying and pasting Angular material code for a datePicker and input, I encountered an error specifically related to the datePicker component. app.module import {MaterialModule} from '@angular/material'; @NgModule({ imports: [ ... Materia ...

What is the reason behind Jest's failure with the error message "component is a part of the declaration of 2 modules"?

While running a test in an Angular (NX) project, I encountered the following exception: Error: Type FooComponent is part of the declarations of 2 modules: FooComponentModule and FooComponentModule! Please consider moving FooComponent to a higher module tha ...

Steps to enable the submit button in angular

Here's the code snippet: SampleComponent.html <nz-radio-group formControlName="radiostatus" [(ngModel)]="radioValue" (ngModelChange)="onChangeStatus($event)"> <label nz-radio nzValue="passed">Passed</label> <label nz-rad ...

Error-throwing constructor unit test

In my code, I have implemented a constructor that takes in a configuration object. Within this constructor, I perform validations on the object. If the validation fails, I aim to throw an error that clearly describes the issue to the user. Now, I am wonde ...

Getting to grips with the intricacies of the Gradle "task" syntax

I'm having trouble grasping the syntax of Gradle tasks. After following a tutorial, I created a build.gradle file for building Angular4/SpringBoots projects with Gradle. The build.gradle file includes several task blocks: // added our development b ...

Taking advantage of Input decorator to access several properties in Angular 2

I am currently working on a component that is designed to receive two inputs through its selector. However, I would like to make it flexible enough to accept any number of inputs from various components. Initially, I tried using a single @Input() decorator ...