在角6呼吁事件的其它部件的功能在一个部件(call function of other compon

2019-10-28 10:59发布

我使用Angular 6

我有一个组件HeaderComponent其HTML包含输入字段一样

header.component.html

<form>
    <input (keyup)="search($event)">
</form>

<app-search-result-card *ngIf="searchQuery.length > 3"
                          [searchQuery]="searchQuery">
</app-search-result-card>

SearchResultComponent必须执行搜索功能

export class SearchResultCardComponent implements OnInit {

  @Input() searchQuery: string;
  searching = true;

  constructor(
    private searchService: SearchService
  ) { }

  ngOnInit() {
    this.performSearch();
  }

  /**
   * Perform search
   */
  performSearch() {
    this.searching = true;
    console.log(this.searchQuery);
    this.searching = false;
  }
}

我如何调用该函数performSearch上的变化searchQuery值上keyup在输入字段?

Answer 1:

使用ngModel指令在你的表单中使用绑定

<form>
    <input type="text" [(ngModel)]="searchQuery" name="searchQuery">
</form>

<search [searchQuery]="searchQuery"></search>

在标题组件使SEARCHQUERY为空字符串

searchQuery:string = ''

在你的搜索组件使用的生命周期挂钩ngOnChanges检测输入属性发生变化或者您可以使用欢迎使用属性的制定者。 在ngOnChanges生命周期中你会得到SEARCHQUERY属性值。 在那里,你可以执行搜索功能

export class SearchComponent implements OnChanges  {
  searching: boolean
  @Input() searchQuery: string;


  ngOnChanges(changes:SimpleChanges){
    if(changes.searchQuery.currentValue.length > 3){
      this.performSearch()
    }
  }

   performSearch() {
    this.searching = true;
    console.log(this.searchQuery);
    this.searching = false;
  }
}

演示链接



Answer 2:

使用output事件为同一结合

<app-search-result-card *ngIf="searchQuery.length > 3"
                          [searchQuery]="searchQuery"
                          (queryResult)='queryResult($event)'>
</app-search-result-card>


Answer 3:

header.component.ts

// use ViewChild to get instance of SearchResultCardComponent in template
@ViewChild(SearchResultCardComponent) src: SearchResultCardComponent;

search(event) {
  this.src.performSearch();
}

在这里你可以如何调用子方法的父母,但我建议你重构你的设备,请SearchResultCardComponent组件假人,从父母只得到搜索结果。



Answer 4:

注入SearchResultCardComponentHeaderComponent并调用其功能performSearch()searchKey.length > 3如下:

在你HeaderComponent.ts

constructor(private searchResultCardComponent: SearchResultCardComponent){}

search(searchKey: string) {
    if(searchKey.length <= 3) return;
    let searchResult = this.searchResultCardComponent.performSearch(searchKey);
}


文章来源: call function of other component on event in one component in Angular 6