Angular:如何将数据从父组件传递到子组件?

时间:2018-12-10 09:19:41

标签: angular

在父组件中给出输入时如何过滤列表?

当列表和搜索框位于同一组件中时,我可以进行过滤,但是当列表和搜索框位于不同组件中时,则无法进行过滤。我尝试使用不起作用的@Intput。

我的代码:

parent.html

<div style="height:10%;">
   <input type="text" placeholder="search here.." class="search_box" [(ngModel)]="term">
<app-environment [term]="term"></app-environment>
 </div>

child.html

   <tr *ngFor="let environ of environmentLists | filter:term; let i = index">
            <td>{{environ.rgn}}</td>
            <td ng-maxlength="5">{{environ.serverType}}</td>
            <td>{{environ.hostName}}</td>
            <td>{{environ.createDate}}</td>
        </tr>

child.js

@Component({
  selector: 'app-environment',
  templateUrl: './environment.component.html',
  styleUrls: ['./environment.component.css'],
  providers: [DashboardService]
})
export class EnvironmentComponent implements OnInit {

  environmentLists: String[];
 @Input() term: string;

  constructor(private _dashboardService: DashboardService) {

  }

  ngOnInit() {
    this._dashboardService.getEnvironments()
      .subscribe((environmentData) => this.environmentLists = environmentData);
  }



}

2 个答案:

答案 0 :(得分:0)

您需要确保filter管道已实现并且在子组件中可用。注意:这将在每次视图更新时重新过滤列表,可能效率不高。 例如

@Pipe({name: 'filter'})
export class FilterPipe implements PipeTransform {
  transform(values: string[], term: string): number {
    return values.filter(value => value.indexOf(term) > -1);
  }
}

最好仅在搜索字词发生变化时过滤列表,例如

export class EnvironmentComponent implements OnInit {

  environmentLists: String[];
  environmentListsFiltered: String[];
  @Input() set term(term: string) {
    this._term = term;
    this.environmentListsFiltered = environmentLists.filter(item => item.indexOf(term)>-1);
  }
  get term(): string {
    return this._term;
  };
  private _term: string;
}

并在模板中使用它:

<tr *ngFor="let environ of environmentListsFiltered; let i = index">

您也可以使用可观察性来更好地进行变更管理,请参见例如https://stackblitz.com/github/bithost-gmbh/ngx-mat-select-search-example

答案 1 :(得分:0)

这可能是最简单的方法,即创建一个与filter相关的方法,并在每次模型更改时从父级调用此方法

父母

<input [(ngModel)]="term"  (ngModelChange)="child.filter(term)">
<app-child #child></app-child>

孩子

  public filter(term: string = "") {
    term = term.trim(); // remove empty space 
    if (term) { // if the user send an empty string like spaces
      this.filterd = this.list.filter((v: string) => v.includes(term));
    } else { // reset 
      this.filterd = this.list;
    }
  }

stackblitz demo