Search code examples
angularsearchngforngmodel

Pass {(ngModel)} through components in *ngFor


how can i pass a {(ngModel)} in a other component to use in a *ngFor? I have a navbar with a input to search and im using ng2-search-filter, i need to pass the {(ngModel)} in a other component (the table with the results) but i cant.

Template: app.component.html

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

Template: navbar.component.html

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

Template: table.component.html

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

filter:stringToLook dont work (stringToLook is Undefined).


Component: table.component.ts

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

UPDATE

I read the doc and i did it but dont work.

Parent Component

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);
  }

Child Component

ts

@Input('filter') filter: string;

Thanks so much


Solution

  • I fixed using a service, in the service i create the variable String and a Setter,in parent component i set the value and in child component i get the value.

    Service

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

    Parent

    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 constructor(..., private service: Service)

    Child

    Simply when you need, use service.filter