Search code examples
angularangular6angular-pipe

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


I'm searching for the products with the pipe. The pipe is working when [(ngModel)] in product.component.html but is not working when [(ngModel)] in app.component.html.

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>

How to fix this?

Thanks.


Solution

  • You need declare @Input decorator inside product.component.ts file.

    In 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
    }
    

    In product.component.html

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

    Now in you app.component.html like:

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

    Hope this will work for you!!!!