通过{ngng)}通过* ngFor中的组件

时间:2019-10-22 10:39:51

标签: angular search ngfor ngmodel

如何在其他组件中传递{(ngModel)}以在* ngFor中使用? 我有一个导航栏,其中包含要搜索的输入和使用ng2-search-filter的即时消息,我需要在其他组件(带有结果的表)中传递{(ngModel)},但我不能。

模板:app.component.html

    <div [@routeAnimations]="o.isActivated ? o.activatedRoute : ''" class="main-content">
      <app-navbar></app-navbar>
      <router-outlet #o="outlet"></router-outlet>
    </div>

模板:navbar.component.html

    <input class="form-control" placeholder="Sarch" type="text" name="filter" [(ngModel)]="stringToLook">

模板:table.component.html

    <tr *ngFor="let object of (objects$ | async) | filter:filter | paginate: config | orderBy: key : reverse">

filter:stringToLook不起作用(stringToLook未定义)。


组件:table.component.ts

    .....
        @Input() stringToLook: any;
    .....

更新

我阅读了文档并做到了,但是没有用。

父项

html

<form (submit)="setText(filter.value)" >
            <input class="form-control" name="filter" placeholder="Cerca" type="text" #filter>
            <button type="submit" style="display:none">hidden submit</button>
          </form>

ts

filter: string;
setText(filter: string) {
  this.filter = filter;
  console.log(this.filter);
  }

子组件

ts

@Input('filter') filter: string;

非常感谢

2 个答案:

答案 0 :(得分:0)

我使用服务进行了固定,在服务中我创建了变量String和Setter,在父组件中设置了值,在子组件中获得了值。

服务

filter: string;
setText(filter: string) {
    this.filter = filter;
    console.log(this.filter);
  }

父母

Html

<form (submit)="service.setText(filter.value)" >
            <input class="form-control" name="filter" placeholder="Cerca" type="text" #filter>
            <button type="submit" style="display:none">hidden submit</button>
          </form>

TS 构造函数(...,私有服务:Service)

孩子

仅在需要时使用service.filter

答案 1 :(得分:0)

通常,当我们要在组件之间共享数据时,服务是最佳选择。

我建议您使用一种更加异步的方式,使用rxjs可观察对象和主题从服务中获取和设置数据。

更多信息:angular-8-communication-between-components-using-subject-and-observable

服务

_filter = new BehaviorSubject<string>('');
filter$ = this._filter.asObservable();

组件

ngOnInit() {
  this.subscription = this.service.filter$.subscribe(x => this.filter = x);
}

ngOnDestroy() {
  this.subscription.unsubscribe();
}

onChangeFilter(filterNewValue: any) {
  this.service._filter.next(filterNewValue)
}