变量之间的共享价值在Angular中不起作用

时间:2018-09-05 09:01:24

标签: javascript angular

我正在用Angular 5实现一个搜索框。我有一个用于搜索框的组件,另一个是用于搜索结果的组件。当我通过输入元素将值传递给search.component.html中的变量'v'时,它会更新search-result.component.ts中的'v',因此在 {{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>

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>

2 个答案:

答案 0 :(得分:0)

您需要移动以下行:

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

这样,用户每次点击搜索按钮时,阵列都会更新。

答案 1 :(得分:0)

您需要移动过滤器,还需要将值分配给 receiveValue 方法内部

像这样

 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演示