簡體   English   中英

如何從Angular 6中的另一個組件獲取[(ngmodel)]

[英]how to get [(ngmodel)] from another component in Angular 6

我在尋找帶有管子的產品。 該管道在product.component.html中的[[ngModel)]時起作用,但在app.component.html中的[(ngModel)]時則不起作用。

product-find.pipe.ts:

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

@Pipe({
  name: 'productFind'
})

export class ProductFindPipe implements PipeTransform {

  transform(value: Product[], filterText?: string): Product[] {
    filterText = filterText ? filterText.toLocaleLowerCase() : null;
    console.log(filterText);
    return filterText ? value.filter((x: Product) => x.productName.toLocaleLowerCase().indexOf(filterText) >= 0) : value;
  }

}

app.component.html:

...

<input [(ngModel)]="filterText" name="filterText" class="form-control" type="search" placeholder="Search" aria-label="Search">

...

product.component.html:

<div>
  <input class="form-control" type="search" placeholder="Search" aria-label="Search">
</div>
<div>
  <ul class="list-group">
    <li *ngFor="let product of products |productFind:filterText" class="list-group-item">
      ...
    </li>
  </ul>
</div>

如何解決這個問題?

謝謝。

您需要在product.component.ts文件中聲明@Input裝飾器。

在product.component.ts中:

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-product',
  templateUrl: 'your-template-url-here
})
export class ProductComponent {

    @Input() filterText: any; 

        //rest of your code here
}

在product.component.html中

<div>
    <ul class="list-group">
       <li *ngFor="let product of products |productFind:filterText" class="list-group-item">
                        ...
        </li>
    </ul>
</div>

現在在您的app.component.html中,如下所示:

<input [(ngModel)]="filterText" name="filterText" class="form-control" type="search" placeholder="Search" aria-label="Search">
<app-product [filterText]="filterText"><app-product>

希望這對您有用!!!

解決問題的兩種可能方法:

  1. 在product.component.ts中定義filterText,並在product.component.html中使用[(ngModel)] =“ filterText”。 從app.component中刪除輸入框。

  2. 使用@Input將父組件(即app.component)的filterText變量傳遞給子product.component

app.component.html:

<app-product [filterText]="filterText"></app-product>

product.component.ts

@Input
filterText : string;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM