问题
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
<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>
category-component.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
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;
}
}
回答1:
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
Change the value of appService.category
from category-component
and it will automatically reflect in the product-component
.
来源:https://stackoverflow.com/questions/51337309/angular-4-ngmodel-between-components