Bạn nên sử dụng Pipe và Observables.
Dưới đây là ví dụ đơn giản cho sự cố của bạn:
Mỗi khi người dùng chọn giá trị, sự kiện thay đổi sẽ được kích hoạt. Với sự kiện, bạn có thể dễ dàng nhận được giá trị và chuyển nó tới luồng có thể quan sát được.
Bạn có thể nhận được quyền truy cập vào các quan sát được từ SelectDataComponent của bạn để thành phần bảng của bạn (AppComponent) thông qua một ref yếu tố (#)
Cung cấp Quan sát để ống myCustomFilter của bạn và đăng ký với các quan sát qua ống async được cung cấp bởi góc cạnh.
*ngFor="let data of someData | myCustomFilter: (selectDataComp.selectedValues$ | async)
AppComponent
import {Component} from '@angular/core';
@Component({
selector: 'app-root',
template: `
<app-select-data #selectDataComp></app-select-data>
<table>
<th>Value</th>
<th>id</th>
<tr *ngFor="let data of someData | myCustomFilter:
(selectDataComp.selectedValues$ | async)">
<td>{{data?.value}}</td>
<td>{{data?.id}}</td>
</tr>
</table>
`,
styles: []
})
export class AppComponent {
someData = [
{ value: 'ABC', id: '123'},
{ value: 'ABC', id: '12'},
{ value: 'DEF', id: '23'},
{ value: 'DEF', id: '1233'},
{ value: 'ABC', id: '13'},
{ value: 'DEF', id: '1'},
{ value: 'DEF', id: '34'},
{ value: 'ABC', id: '56'},
{ value: 'ABC', id: '13'},
{ value: 'DEF', id: '123'},
{ value: 'HIJ', id: '113'}
];
}
SelectDataComponent
import { Component } from '@angular/core';
import {Subject} from 'rxjs/Subject';
@Component({
selector: 'app-select-data',
template: `
<div>
<select (change)="onChange($event.target.value)">
<option value="">--please select--</option>
<option *ngFor="let option of options"
[value]="option">
{{ option }}
</option>
</select>
</div>
`,
styles: []
})
export class SelectDataComponent {
public selectedValues$: Subject<string> = new Subject();
public options = ['ABC', 'DEF'];
onChange(selectedValue) {
this.selectedValues$.next(selectedValue);
}
}
myCustomFilter
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'myCustomFilter'
})
export class MyCustomFilterPipe implements PipeTransform {
transform(data: any, toFilter: string): any {
if (!toFilter) { return data; }
return data.filter(d => d.value === toFilter);
}
}
AppModule
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {BrowserAnimationsModule} from '@angular/platform-
browser/animations';
import { SelectDataComponent } from './select-data.component';
import { MyCustomFilterPipe } from './my-custom-filter.pipe';
@NgModule({
declarations: [
AppComponent,
SelectDataComponent,
MyCustomFilterPipe,
],
imports: [
BrowserModule,
BrowserAnimationsModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }