Utilizing the angular form, I have created a search bar on the "search page" ("/search"). I've noticed that when I search for something, like "testing word", then navigate to the home page ("/") and return to the search page, the input in the search bar still shows "testing word".
I attempted using unsubscribe
in ngOnDestroy
, but it doesn't seem to work (ngOnDestroy is triggered based on the console log "haha"). While I know that resetting the searchTerm
with a button click event would work, my goal is to automatically reset the values when leaving the search page. How can I achieve this?
Thank you.
<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")
}
}