【问题标题】:Angular 4 ngModel between components组件之间的Angular 4 ngModel
【发布时间】:2018-07-14 09:52:59
【问题描述】:

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

产品组件.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;
 }

}

【问题讨论】:

  • product-componentcategory-component 是兄弟姐妹吗?他们有共同的父母吗?
  • 嗨@AnkitSharma 他们都没有父母。我可以从 product-component 访问 filterCategory(ngModule) 值吗?
  • 不,您可能无法访问 ngModel 值。您可能会做的是,使用服务来传达所需的数据。请创建一个演示 stackblitz,以便我们为您提供帮助。谢谢
  • 我可以直接使用我的分支创建demo吗?
  • 你的分公司?是在 GitHub 上吗?

标签: node.js angular angular-ngmodel angularjs-ng-model


【解决方案1】:

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

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

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

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

appService.category 的值从category-component 更改为自动反映在product-component 中。

【讨论】:

    猜你喜欢
    • 2019-06-06
    • 1970-01-01
    • 1970-01-01
    • 2018-09-27
    • 1970-01-01
    • 2019-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多