首页 > 解决方案 > 如何动态过滤角度json文件?

问题描述

我想根据我输入的字母搜索我的 json 文件,它应该被相应地过滤,这是我的 json 文件:

constructor(private service:ServiceService) { }
ngOnInit(): void {
     this.x="123";
     this.service.getListofTurbines(this.x).subscribe(s=>{
     this.rslt=s;

 })

使用过滤器它会返回正确的匹配项,但我如何动态搜索它?

标签: angulartypescript

解决方案


打字是在控制中发生的动作,因此在角度最好的方法是如果你创建一个FormGroup和一个FormControl

为了示例,我们将调用您的表单listForm和控件searchControl

  listForm: FormGroup;

...

//this could on ngOnInit declaring the formControl and the formGroup
   this.listForm = this.formBuilder.
   group({ item: this.formBuilder.array([]), 
      'searchControl': new FormControl("") });

...

//this could on ngOnInit observing the value changes when typing occurs
    this.listForm.controls['searchControl'].valueChanges .pipe(
          startwith(''),
          debounceTime(500) /*to avoid searching every letter, increase time to reduce searches*/)
          .subscribe((value) => {
              //and here your perform your search

推荐阅读