如何在 angular 10 中自动重置输入值 (formGroup)?

How to auto reset input value (formGroup) in angular 10?

我正在使用 angular 表单在“搜索页面”(“/search”)中创建一个搜索栏。我注意到我是否搜索过某些东西,例如“测试词”。然后,我转到主页(“/”)并 回到搜索页面,搜索栏输入,“测试词”依然存在

我以为我在 ngOnDestroy 中使用了 unsubscribe,但它似乎不起作用(ngOnDestroy 是根据控制台日志“哈哈”调用的)。我知道如果使用按钮单击事件重置 searchTerm 会起作用。但是,我希望在我们离开搜索页面时自动重置这些值。我该如何实现?

谢谢。

<form [formGroup]="searchForm" novalidate>
  <mat-form-field floatLabel="never">
    <input matInput type="type" autocomplete="off" formControlName="search">
    <mat-placeholder>Search</mat-placeholder>
  </mat-form-field>
  <a mat-icon-button aria-label="Search" (click)="emitState()">
    <mat-icon>search</mat-icon>
  </a>
</form>

---------------

export class SearchComponent implements OnInit, OnDestroy
{
  searchForm: FormGroup;
  private searchSub!: Subscription;
  constructor(private formBuilder: FormBuilder) {
    super();
    this.searchForm = this.formBuilder.group({
      search: ['', []],
    });
  }

  ngOnInit(): void {
    const searchTerms = this.values[0].value as string;
    this.searchForm.get('search')?.setValue(searchTerms);

    this.searchSub = this.searchForm.controls.search.valueChanges
      .pipe(debounceTime(400), distinctUntilChanged())
      .subscribe(
        (term) => {
          this.values[0].value = term;
          this.emitState();
        },
        (err) => console.log(err)
      );
  }

  ngOnDestroy(): void {
    this.searchSub.unsubscribe();
    console.log("haha")
  }
}

调用 this.searchSub.unsubscribe 只会退订您要列出的值更改。我认为您应该能够将 this.searchForm.reset() 添加到您的 ngOnDestroy 以清除表单。

ngOnDestroy(): void {
  this.searchSub.unsubscribe();
  this.searchForm.reset()
  console.log("haha")
}