加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读