自定义管道到项目中
- 创建一个搜索框,根据关键字自动展示包含关键字的商品
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<input #KeyWord type="text" class="form-control" placeholder="请输入商品名称" [formControl]="titleFilter">
</div>
</div>
</div>
private keyword:string;
private titleFilter:FormControl;
constructor(private productService: ProductService) {
this.titleFilter.valueChanges
.pipe(debounceTime(500))
.subscribe(
value=>this.keyword=value
)
}
- 编辑管道,传入一个list商品列表也就是过滤的目标,第二个参数是filterFiled根据商品的哪个字段去过滤,第三个字段是输入keyword的关键字,如果过滤字段或者关键字没有输入,就返回整个商品列表(即页面无变化),如果filterFiled告诉传入得到字段是商品标题,fieldValue就会拿到传入的商品的名称
export class FilterPipe implements PipeTransform {
transform(list: any[], filterFiled: string, keyWord: string): any {
if (!filterFiled || !keyWord) {
return list;
}
return list.filter(item => {
let fieldValue = item[filterFiled];
return fieldValue.toLowerCase().indexOf(keyWord) >= 0;
});
}
}
- 使用这个管道完成根据关键字过滤操作
<div class="col-md-4 col-sm-4 col-lg-4" *ngFor="let product of products | filter:'title':keyword">
组件间通讯
- 组件的输入输出属性,使用中间人模式传递数据,组件生命周期以及angular的变化发现机制
- 输入属性,组件的输入属性是指被@Input装饰器注解的属性,用来从父组件接收数据,新建一个子组件order,用@Input注解两个变量,并将其展示在子组件页面上
export class OrderComponent implements OnInit {
@Input()
stockCode:string;
@Input
amount:number;
constructor() { }
ngOnInit() {
}
}
<div>子组件</div>
<div>买{{amount}}手{{stockCode}}股票</div>
- 在父组件中,将父组件的数据传递给子组件使用
<div>
父组件
</div>
<div>
<input type="text" placeholder="输入股票代码" [(ngModel)]="stock">
<app-order [stockCode]="stock" [amount]="100" ]></app-order>
</div>
- 输入属性是单向绑定,子组件的数据变化不会改变父组件数据
- 输入属性和路由参数传递数据的不同
- 输入属性是通过属性来传递数据的,这种传递只能在有父子组件关系从父组件传递数据给子组件
- 路由参数是通过构造函数依赖注入一个routeInfo:ActivatedRoute对象,通过这个对象的参数订阅或者参数快照,来获取外面传入的参数
- 输出属性
- angular组件可以使用一个event对象来发射自定义的事件,这个事件会被其他组件处理,在响应式编程中既可以作为被观察者,也可以作为观察者,也就是说既可以发射自定义事件,也可以通过来订阅它发射出来的事件流
和输入属性相同输出属性使用@Output
export class PriceQuoteComponent implements OnInit {
stockCode:string = "IBM";
price:number;
@Output
lastPrice:EventEmitter<PriceQuote>= new EventEmitter();
constructor() {
setInterval(()=>{
let priceQuote:PriceQuote = new PriceQuote(this.stockCode,100*Math.random());
this.price=priceQuote.lastPrice;
this.lastPrice.emit(priceQuote);
},1000);
}
ngOnInit() {
}
}
export class PriceQuote {
constructor(public stockCode:string,
public lastPrice:number)
{
}
}
export class AppComponent {
stock = "";
priceQuote:PriceQuote = new PriceQuote("",0);
}
<div>
股票代码{{priceQuote.stockCode}}
价格{{priceQuote.lastPrice}}
</div>