我从事过角度4应用。我的要求是: - 我在标题组件上有一个搜索按钮,如果我搜索任何内容,请转到搜索组件并显示结果。但是当我再次在标题中搜索时,它不会重新加载搜索组件。
请告诉我们如何在点击搜索按钮上重新加载组件。
你将按照这些方式写一些东西。请在下次粘贴您自己的代码,以便人们更方便地提供帮助。
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { SearchService } from '[your own search service]';
export class MyComponent {
items : { id: number, name: string}[];
searchForm : FormGroup;
constructor(
private searchService : SearchService,
private formBuilder : FormBuilder ) {
this.searchForm = this.formBuilder.group( {
searchField : ""
} );
}
ngOnInit() {
this.search();
}
search() {
let searchValue = this.searchForm.get( "searchField" ).value();
// Your search service should return an Observable
this.searchService.search( searchValue ).subscribe(
data => {
// Refreshes search result
this.items = data.json();
},
error => {
// Error handling
}
);
}
}
<table>
<tbody>
<tr *ngFor="let item of items">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
</tr>
</tbody>
</table>
......
<form [formGroup]="searchForm">
<input type="text" placeholder="Search Field" formControlName="searchField" />
<button (click)="search()">Search</button>
</form>
每当您单击标题组件中的搜索按钮或单击Enter时,请务必重新加载search component
。
// whenever enter is hit anywhere in this component, search() will be called
@HostListener('keyup.enter', ['searchInput']) search(searchInput: string) {
// check for minimum chanractor
if (searchText.length > this.MIN_SEARCH_LENGTH) {
this.error = false;
// now navigate to the search component
this.router.navigate(['search', searchInput], {
queryParams: {
match: this.match.join(',')
}
});
} else {
this.error = true;
}
}
在上面的代码中,每次搜索导航到搜索组件时都会创建一个新实例。