Properly setting up a personalized input component in Angular 6

After attempting to create a custom input component with debounce functionality, I decided to follow the advice provided in this helpful suggestion.

Although the debounce feature is working, I encountered an issue where the initial value of the input component was not being correctly set.

Below is my implementation:

app.component.ts

import { Component } from '@angular/core';
import { DebInputComponent } from './deb-input/deb-input.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  test:string ='test';
}

app.component.html

  <deb-input [(ngModel)]="test" type="text" label="Test" ngDefaultControl>
  </deb-input>
<div>{{test}}</div>

deb-input.component.ts

import { Observable, Subject } from 'rxjs';
import { debounceTime, distinctUntilChanged } from 'rxjs/operators';
import { Component, Input }   from '@angular/core';

@Component({
  selector: 'deb-input',
  templateUrl: './deb-input.component.html',
  styleUrls: ['./deb-input.component.css'],
  providers: []
})

export class DebInputComponent {
    @Input() label: string;
    @Input() type: string="text";
    @Input() model: string;
    modelChanged: Subject<string> = new Subject<string>();

    constructor() {
     this.modelChanged
      .pipe(debounceTime(1000))
      .pipe(distinctUntilChanged())
      .subscribe(newValue => {this.model = newValue;
        console.log(this.model)});
    }

    changed(text: string) {
        this.modelChanged.next(text);
    }
}

deb-input.component.html

 <div>
 <span>{{label}}</span>
 <input [(ngModel)]='model' (ngModelChange)='changed($event)' [type]='type' ngDefaultControl/>
</div>

In order to ensure that the model within the deb-input component is correctly set to "test," what steps should I take?

Answer №1

Make sure to use the name of your component input instead of ngmodel.

<deb-input [model]="test" type="text" label="Test" ngDefaultControl>
  </deb-input>

Edit

If you need two-way binding for your component, add an eventEmitter like this:

@Input() model: string;
@Output() modelChange = new EventEmitter<string>();
modelChanged: Subject<string> = new Subject<string>();
@Output() modelChangeEvt = new EventEmitter<string>();

 constructor() {
 this.modelChanged
  .pipe(debounceTime(1000))
  .pipe(distinctUntilChanged())
  .subscribe(newValue => {this.model = newValue;
    this.modelChangeEvt.emit(newValue);
    console.log(this.model)});
}

To implement two-way binding in HTML, use the following syntax:

<deb-input [(model)]="test" type="text" label="Test" ngDefaultControl></deb-input>

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

What is the best way to receive a notification once the final observable has completed emitting its values?

In the past, we only made one call to the API reqFinanceDataWithFilters(req): Observable<any> { return this.http.post(env.baseUrl + req.url, req.filters) .pipe(map(this.extractResults)); } However, the response from this single request was a ...

What is the method for initializing fancybox with the precise image index?

My current usage of fancybox involves the following code snippet: $("a[rel=Fancy" + UserId + "].Items").fancybox({ 'autoscale': 'false', 'cyclic': true, 'transitionIn': 'elastic', & ...

Bringing in a standard library to a Vue single-page application

Struggling to grasp what should be a straightforward task, I'm open to the idea that my current approach may not be the best way forward. Currently, we are updating our processes and refining some of the functions within a .js file that houses numerou ...

Firestore is diligently fetching data with each new insert or update

this.unsubscribe= this.firestore.collection('mycollection').ref.where("somecase","==","myvalue") .onSnapshot((data=>{})); Striving to implement real-time data on my website, I encountered an issue with Firestore loading all data for ea ...

Updates in dropdown events when options data has been modified

Hey there, I'm wondering about dropdown events. Let's say I have two dropdowns. When a selection is made in the first dropdown, all options in the second dropdown are replaced with new ones. For example, let's say the first dropdown has thes ...

Verifying the user's email and password for authentication

Is there a way to verify the authenticity of the email and password entered in the form, so that I can redirect to a new page? Unfortunately, upon reloading the page, the validation process seems to fail in checking whether the user email and password are ...

Displaying information before completing map zoom and pan on Bing AJAX map

When using my Bing Ajax Map app, users are presented with a list of locations to choose from. Upon clicking on a row, the map centers and zooms in on the selected location. However, I've encountered an issue where the info window loads before the map ...

Top method for enhancing outside libraries in AngularJs

Currently, I am utilizing the angular bootstrap ui third party library as a dependency in my angular application. One question that is on my mind is what would be the most effective method to enhance the functionality of directives and controllers within t ...

Tips for altering the appearance of a dropped item using JQueryUI sortable

I have a straightforward website where I need to implement the ability to drag and drop styled DIV elements between two containers. Utilizing JQueryUI's sortable function, this behavior was successfully achieved with the following code: $("#active-co ...

Encountering an Uncaught TypeError in Reactjs: The property 'groupsData' of null is not readable

While working on a ReactJs component, I encountered an issue with two basic ajax calls to different APIs. Even though I am sure that the URLs are functioning and returning data, I keep getting the following error message: Uncaught TypeError: Cannot read p ...

Clone a specific link within a div using jQuery only one time

I have a group of divs and I want to copy the link from the first div and put it into the last div (mobile-link). Currently, it is either duplicating all the links and inserting them all at once, or if I use :eq(0), it's placing the first link in each ...

md-list-item containing md-radio-button

Trying to tackle this particular issue: https://github.com/angular/material2/issues/1518 I want the ability to click anywhere on the line of my md-item and have it trigger the radio-button action. settings.component.html : <md-radio-group [(ngModel) ...

When incorporating Angular-tree-component into the project, an error is thrown in the Console: "(SystemJS) ctorParameters.map is not a function."

I utilized this guide to integrate the angular-tree-component plugin. Despite following the instructions precisely, I encountered the following error when running the application: Error: (SystemJS) ctorParameters.map is not a function(…) Here is an exc ...

Angular Fire Store - Issue "No Common Properties Found with type 'GetOptions'."

My goal is to retrieve a specific value from a document. I attempted the following approach: getAuthorData(){ const test = this.afs.collection('Authors').doc('Test').get('name'); console.log(test); } However, I encountered t ...

What is the method for extracting latitude and longitude values individually from JSON data?

Upon receiving the JSON response from the Google Maps API stored in a variable named 'obj', I noticed that alerting obj.name returns "Pancakes on the Rocks". To access the icon, I can use obj.icon. However, I am struggling to retrieve separate va ...

The second parameter of the Ajax request is not defined

Having an issue with my Ajax request in Vue.js where the second parameter is logging as undefined in the console. I've been trying to fix this problem but haven't found a solution yet. This is the code snippet for $.ajax(): //$.ajax() to add ag ...

When attempting to store Form input strings in an array upon submission, I find that instead of the desired input strings, the array contains only empty strings. This issue arises while utilizing Functional

My goal is to use functional components in order to store string Form data in an array upon submission. However, when I try using console.log(value) within the handleSubmit function, it returns an empty array. I am struggling to access the user input from ...

New to React and struggling with updating the DOM

Upon receiving a React project, I am faced with the task of performing a complex state update on my DOM. Here is how my component looks: /** @jsx jsx */ import { jsx } from '@emotion/core'; import { Typography } from '@material-ui/core&ap ...

Can you send the value of an Angular-generated input to a function even if it doesn't have an ID associated with it?

Is there a way to make the cells in a dynamically generated table editable? The challenge I am facing is that because the table uses MatTableDataSource in Angular with data from an API, the cell elements cannot have unique IDs. How can I ensure that when a ...

Troubleshooting issues with @HostListener in Angular2 RC1

Created a custom attribute directive called myOptional specifically for use with form inputs, to indicate that certain fields are optional. This is achieved by adding a class to the input and then displaying the optional text through css pseudo element ::a ...