组件之间的 Angular 4 ngModel [英] Angular 4 ngModel between components

查看:28
本文介绍了组件之间的 Angular 4 ngModel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按 categoryId 值过滤我的产品.产品在产品组件中列出.我有一个 categoryFilter 管道,用于过滤产品并返回产品列表.此管道需要 categoryId 但此值在类别组件范围内.所以我的产品组件无法访问它.我应该怎么做才能让它发挥作用?

I'm trying to filter my products by categoryId value. Products are listing in product-component. I have a categoryFilter pipe that filters Products and returns list of Product. This pipe requires categoryId but this value is in category-component scope. So my product-component cannot access it. What should I do to make it work?

product-component.html

product-component.html

<ul class="list-group">
<li class="list-group-item" *ngFor="let product of products |productFilter:filterText|categoryFilter:filterCategory">
  <button (click)="addToCart(product)" class="btn btn-sm btn-primary float-right">
    <i class="fa fa-plus"></i>
    add to cart
  </button>
  <h5>{{product.productName | uppercase}} ({{product.categoryId}})</h5>
  <p>{{product.quantityPerUnit}}</p>
  <h6>{{product.unitPrice | currency:'TRY':'₺'}} (KDV DAHİL: {{product.unitPrice |vatAdded:8 | currency:'TRY':'₺'}})</h6>
</li>

类别组件.html

<select class="form-control" [(ngModel)]="filterCategory">
<option value="" selected="selected">-- Choose Category --</option>
<option *ngFor="let category of categoryList" value=" 
{{category.categoryId}}">{{category.categoryName}}</option>
</select>

category-filter.pipe.ts

category-filter.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';
import { Product } from '../product/product';

@Pipe({
name: 'categoryFilter'
})
export class CategoryFilterPipe implements PipeTransform {

transform(value: Product[], filterCategory?: any): Product[] {
return filterCategory? 
value.filter((p:Product)=>p.categoryId==filterCategory):value;
 }

}

推荐答案

您可以使用服务在无法通过事件进行通信的两个组件之间共享数据.

You may share data between two components that cannot communicate via Events by using services.

您可以在两个组件中注入一个服务并从那里访问所需的字段.更改服务字段的值将反映在两个组件中.

You can inject a service in the two components and access the required field from there. Changing the value of service's field will reflect in both the components.

请看下面的演示,了解如何实施.

Please take a look at the below demo to get some sort of idea on how to implement.

https://stackblitz.com/edit/angular-prge5p?file=src%2Fapp%2Fproduct.component.ts

appService.category 的值从 category-component 更改,它会自动反映在 product-component 中.

Change the value of appService.category from category-component and it will automatically reflect in the product-component.

这篇关于组件之间的 Angular 4 ngModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆