Доля значения между переменными не работает в Angular - PullRequest
0 голосов
/ 05 сентября 2018

Я реализую окно поиска по Angular 5. У меня есть компонент для окна поиска и еще один компонент для результата поиска. Когда я передаю значение через элемент ввода в переменную 'v' в search.component.html, он обновляет 'v' в search-result.component.ts, поэтому {{v}} в html показывает значение, которое Я вошел.

Чтобы отфильтровать массив, я беру от 'v' до 'term' и выполняю функцию фильтра. Но после загрузки страницы он показывает только значение {{v}} и не показывает {{term}} и {{filterarray}}

Что здесь не так?

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>

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>

Ответы [ 2 ]

0 голосов
/ 05 сентября 2018

Вам нужно переместить фильтр, а также присвоить значение внутри receiveValue method

вот так,

 v: string;

  term: string;

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

  constructor() { }

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

  }

здесь Stackblitz демо

0 голосов
/ 05 сентября 2018

Вам нужно переместить эту строку:

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

внутрь:

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

Так что-то вроде этого:

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

Таким образом, каждый раз, когда пользователь нажимает кнопку поиска, массив будет обновляться.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...