2个组件之间的连接

时间:2018-04-16 11:34:20

标签: php angular typescript dom angular2-routing

我正在实施一个角度例子。我在navbar组件中有一个搜索输入,我想在另一个组件中显示搜索结果,但我发现第二个组件将如何知道我将其放入搜索输入文本中的值的问题。 这是我的navbar.ts文件:

import { Component, OnInit, Input } from '@angular/core';
import { Router } from '@angular/router';
import { RechercheService } from 

   '../../services/recherche/recherche.service';
 @Component({
     selector: 'navbar',
     templateUrl: './navbar.component.html',
     styleUrls: ['./navbar.component.scss']
            })
export class NavbarComponent implements OnInit {
  name: string ;
  listUsers;
  constructor(){}

    ngOnInit() {

    }



search() { 
    let list = this.rechercheService.recherche();
    if(this.name.length>2) {    
        let searchText = (this.name).toLowerCase();
        this.listUsers= list.filter( it => {
          return it.name.toLowerCase().includes(searchText);           
    });
    if(this.listUsers.length>0){
      this.sidenav.open(); 
    }
    else {
      this.sidenav.close();
    }
    }
      console.log(this.listUsers); 
      this.name = "";

     }
   }

这是我的navbar.html:

<div  class="col-3">
        <div class="input-group mb-2">
            <span class="borderColor rounded-left text-center"  
        (click)="search()"><mat-icon class="blueIcon loupeIcon" 
      fontIcon="icon-search"></mat-icon></span>
            <input type="text" class="form-control color" 
        placeholder="search" [(ngModel)]="name" >
            <button class="btn-al-blue rounded-right" type="submit" >more 

            creteria</button>   
        </div>

    </div>

我想在另一个名为second的组件中显示搜索结果。 我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

为同一个

创建共享服务
// Search Control
searchFilter = new Subject<any>();
searchFiltered = this.searchFilter.asObservable();
emitSearchFilter(value) {
    this.searchFilter.next(value);
}

从导航栏组件发出,如

this.navbarService.emitSearchFilter('search keyword');

并订阅另一个组件,如

this.navbarService.searchFiltered.subscribe(value => {
    console.log(value);
  });

不要忘记取消订阅ngDestroy