我有一个绑定到输入域的信号.我正在try 为earchTerm定义一个ffect(),但因为它是用户输入,所以我想go 掉这个效果(即rxjs),这样搜索就不会在每次击键时发生.我不清楚如何做到这一点,文档也没有真正涵盖这种情况.

<input [ngMode]="searchTerm()" (ngModelChnge)="searchTerm.set($event)">

effect(() => { if (this.searchTerm() !== '') { this.search(); } });

推荐答案

在信号中没有内置的debounce 解决方案.但是,您可以创建自定义函数来执行此操作:

function debouncedSignal<T>(input: Signal<T>, timeOutMs = 0): Signal<T> {
  const debounceSignal = signal(input());
  effect(() => {
    const value = input();
    const timeout = setTimeout(() => {
      debounceSignal.set(value);
    }, timeOutMs);
    return () => {
      clearTimeout(timeout);
    };
  });
  return debounceSignal;
}

const itemsList = [
  { name: 'Product A', category: 'Category 1' },
  { name: 'Product B', category: 'Category 2' },
  { name: 'Product C', category: 'Category 1' },
];

@Component({
  selector: 'my-app',
  standalone: true,
  imports: [CommonModule, FormsModule],
  template: `
    <input [ngModel]="searchTerm()" (ngModelChange)="searchTerm.set($any($event))">
    <ul>
      <li *ngFor="let item of items">
        {{item.name}}
      </li>
    </ul>
  `,
})
export class App {
  items = itemsList;

  searchTerm = signal('');

  debounceSearchValue = debouncedSignal(this.searchTerm, 500);

  constructor() {
    effect(() => {
      this.search(this.debounceSearchValue());
    });
  }

  private search(value: string): void {
    if (!value) {
      this.items = itemsList;
    }

    const query = value.toLowerCase();

    this.items = itemsList.filter(
      (item) =>
        item.name.toLowerCase().includes(query) ||
        item.category.toLowerCase().includes(query)
    );
  }
}

这种解决方案非常复杂,所以我建议使用RxJS来获得更干净、更高效的代码

Angular相关问答推荐

使用路由进行测试.为每次测试导航堆栈

独立Angular 零部件不在辅零部件或共享零部件中工作

当元素在元素上使用迭代变量时,如何重构ngFor?

Angular 16独立依赖注入问题

如何将参数传递给Angular 服务

Angular 16 Auth Guard在具有0的服务时给出Null Injector错误;httpclient;被注入

使用 Angular 类构造函数来获取依赖项

我的验证器收到一个始终为空的可观察值

有角.服务.模块构建失败.无法读取未定义的属性(读取文件)

Nx Angular Monorepo 中 cypress 组件测试的代码覆盖率?

升级到 Webpack 5.79.0 后 NX Angular 项目构建失败

如何在 Angular 中顺序执行回调

如何在 form.value 中禁用复选框

angular 13 ng 构建库失败(ivy部分编译模式)

angular material日期 Select 器中的日期不正确

Subject.complete() 是否取消订阅所有听众?

如何使用ngrx和effects 订阅成功回调

错误:formControlName 必须与父 formGroup 指令一起使用.您需要添加一个 formGroup 指令

为什么我们需要`ngDoCheck`

为什么用?模板绑定中的运算符?