Angular 5 – 如何在组件初始化后重新加载组件
发布时间:2020-12-17 10:25:25 所属栏目:安全 来源:网络整理
导读:我在应用程序中有一个搜索功能.当用户点击搜索按钮时,数据在[(ngModel)]中被捕获并传递给服务,URL被重定向到搜索组件的html. 该服务被注入“搜索”组件并显示数据. 现在,当用户输入新的搜索词时,我想刷新现有的搜索组件.这样做的正确方法是什么? search.com
我在应用程序中有一个搜索功能.当用户点击搜索按钮时,数据在[(ngModel)]中被捕获并传递给服务,URL被重定向到搜索组件的html.
该服务被注入“搜索”组件并显示数据. 现在,当用户输入新的搜索词时,我想刷新现有的搜索组件.这样做的正确方法是什么? 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>
我建议使用search.component.ts作为子组件并使用@Input:
app.component.html <form> <input type="text" placeholder="Search" [(ngModel)]="searchInput" name="inputfield"> <app-search [userInput]="searchInput"></app-search> </form> search.component.ts @Input() userInput: string; ngOnChange(){ // this will be called each time userInput changes this.search(); } 有关详细信息,请参阅this article 如果你想点击事件,你需要的只是一个额外的变量,如searchvalue app.component.html <form> <input type="text" placeholder="Search" [(ngModel)]="searchInput" name="inputfield"> <button (click)="searchButtonclick()">Search</button> <app-search [userInput]="searchvalue"></app-search> </form> app.component.ts searchvalue:string; searchButtonclick(){ this.searchvalue = this.searchInput; } search.component.ts // as above (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- Webservice Axis2 Myeclipse
- webservice-axis
- Angularjs,使用data-ng-controller和ng-controller
- Bootstrap CSS——表单(一)
- scala – 如何在应用agg函数之前将十进制值限制为2位数?
- scala – SBT无法将Seq [Object]附加到Seq [ModuleID]
- MDT 2010 - Setting the Computer Description in AD witho
- 如果变量名称存储为字符串如何获取变量值?
- bash – 为什么我可以ping一个服务器,但不能通过ssh连接?
- WebService到底是什么?