3

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 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This is the correct way. Just bind to the literal value - no need for a setter or a local constant.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.