Ad

Share Value Between Variables Is Not Working In Angular

- 1 answer

I'm implementing a search box by Angular 5. I have a component for the search box and another component for search result. When I pass the value through input element to the variable 'v' in search.component.html, It updates the 'v' in search-result.component.ts, so {{v}} in html shows the value that I entered.

To filter the array, I am taking 'v' to 'term' and do the filter function. But, after loading the page, It is only showing the {{v}} value and Not showing the {{term}} and {{filterarray}}

What is the wrong here?

search.component.ts

import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { error } from 'util';

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {

  title = 'app';

  v: string;

  @Output() valueEvent = new EventEmitter<string>();

  constructor(){}

  sendValue(){
    this.valueEvent.emit(this.v)
  }

  ngOnInit()
  }
}

saerch.component.html:

<input type="text" [(ngModel)]="v"><button (click)="sendValue()">Search</button>

saerch-result.component.ts:

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

@Component({
  selector: 'app-search-result',
  templateUrl: './search-result.component.html',
  styleUrls: ['./search-result.component.css']
})
export class SearchResultComponent{

 v: string;

 term: string = this.v;

 array: any[]=[{'id':1,'name':'Jones'},{'id':2,'name':'Duke'},{'id':3,'name':'Frank'},{'id':4,'name':'Jonas'}];
  filterarray: any[];

  constructor(){

    this.filterarray=this.array.filter(f => f.name.includes(this.term)).map(searchname=>searchname.name);

  }

   receiveValue($event){
    this.v = $event
    }
}

search-result.component.html:

<app-search (valueEvent)="receiveValue($event)"></app-search>
<p>{{v}}</p>
<p>{{term}}</p>
<p>{{filterarray}}</p>
Ad

Answer

You need to move this line:

this.filterarray=this.array.filter(f => f.name.includes(this.term)).map(searchname=>searchname.name);

To inside:

receiveValue($event){
   this.v = $event
}

So something like this:

receiveValue($event){
       this.v = $event
       this.filterarray=this.array.filter(f => f.name.includes(this.term)).map(searchname=>searchname.name);
    }

That way every time the user hits search button the array will be updated.

Ad
source: stackoverflow.com
Ad