【发布时间】:2018-08-13 22:14:46
【问题描述】:
我在应用程序中有搜索功能。当用户单击搜索按钮时,数据将在[(ngModel)] 中捕获并传递给服务。 URL 被重定向到SearchComponent 的 HTML。
这个服务被注入到SearchComponent中并显示数据。
当用户输入新的搜索词时,我想刷新现有的SearchComponent。这样做的正确方法是什么?
search.component.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from '../service/data.service';
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {
userInput : string;
constructor(private data : DataService) { }
ngOnInit(){
this.search();
}
search(){
this.userInput = this.data.searchData;
console.log('in search init ' + this.userInput);
this.data.searchData = "";
}
}
app.component.ts
import { Component } from '@angular/core';
import { DataService } from './service/data.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private data : DataService){};
title = 'app';
searchInput: string;
searchButtonclick(){
console.log('search button clicked ' + (this.searchInput));
this.data.searchData = this.searchInput
this.searchInput = "";
}
}
app.component.html
<form>
<input type="text" placeholder="Search" [(ngModel)]="searchInput" name="inputfield">
<a routerLink="/search">
<button (click)="searchButtonclick()">Search</button>
</a>
</form>
【问题讨论】: