如何从Angular 6中的另一个组件获取[(ngmodel)]

时间:2018-07-09 07:14:17

标签: angular angular6 angular-pipe

我正在用管道寻找产品。该管道在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>

该如何解决?

谢谢。

2 个答案:

答案 0 :(得分:2)

您需要在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 :(得分:0)

两种可能的解决方法:

  1. 在product.component.ts中定义filterText,并在product.component.html中使用[(ngModel)] =“ filterText”。从app.component中删除输入框。

  2. 使用@Input

  3. 将父组件(即app.component)的filterText变量传递给子product.component。

app.component.html:

#include <iostream>
#include <string>

class A {

public:

    A() {
        f();
        };

    virtual void f() {
        std::cout<<"A\n";
    }
};

class B : public A {

public:

    B() : A() {}

    virtual void f() override {
        std::cout<<"B\n";
    }

};

int main() {
    B * b = new B();
}

product.component.ts

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