skip to Main Content

I have a simple Angular component which takes a debounce time as an Input parameter. The parameter type is a number with a default value equals to 0. It is used later on as a debounceTime value.

input.component.ts

import { AfterViewInit, Component, Input } from '@angular/core';
import { debounceTime } from 'rxjs';

@Component({
  selector: 'app-input',
  templateUrl: './input.component.html',
  styleUrls: ['./input.component.scss']
})
export class InputComponent implements AfterViewInit {
  @Input() debounce: number = 0;

  ngAfterViewInit(): void {
    //(...).pipe(debounceTime(this.debounce)).subscribe(...);
  }
}

I would like to pass the debounce value from the parent component without binding to the local variable or constant.

app.component.html

<app-input debounce="200"></app-input>

It doesn’t work because debounce value comes as a string type from a template. It does work when I use binding to the local constant. A console error confirms the type.

Error: src/app/app.component.html:3:12 - error TS2322: Type 'string' is not assignable to type 'number'.

I can disable strict templates checks as this is a default for Angular 15 but rxjs "debounceTime" function won’t accept a string parameter.

How can I pass a number directly from the template without using bindings?

2

Answers


  1. Use a setter

    debounce: number = 0;
    @Input() set _debounce(value:any){
       this.debounce=+value;
    }
    

    Or use

    .pipe(debounceTime(+this.debounce)
    

    NOTE: The + is a confortable way to parse a string to number

    Login or Signup to reply.
  2. You can just use [] for input to pass a number like this:

    <app-input [debounce]="200"></app-input>
    

    you’ll now get a number.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search