将布尔值传递给另一个Angular组件

时间:2019-06-18 16:39:55

标签: javascript angular typescript boolean

我有两个Angular组件

results.table和results.query

当用户单击results.query.component中的重置按钮时,我想将表隐藏在results.table.component中

也许我在事件发射器上做错了,或者也许有更好的方法做到这一点

results.table HTML

<div *ngIf='results?.length>0'>
  <table *ngIf="showResults" class='table'>
    <tr>
      <th>Result Name</th>
      <th>Location</th>
    </tr>
    <tbody>
    <ng-template ngFor let-results [ngForOf]='items' let-i="index">
      <tr>
        <td>
          <span>{{result?.description}}</span>
        </td>
        <td>
          <span>{{result?.location}}</span>
        </td>
      </tr>
    </ng-template>
    </tbody>
  </table>
</div>

results.table TS

showResults: boolean = true;

showResults(event) {
    console.log('this is not getting called')
    if (event) {
      this.showResults = false;
    }
}

results.query HTML

<div class="panel-body">
      <form (submit)="onSubmitClicked()">
        <div class="row">
          <div class="form-group col-md-12 col-xs-12">

            <div class="col-xs-12 col-sm-3 col-md-3 col-lg-3">
              <label class="col-md-12 col-xs-12 control-label  no-margin no-padding">Location: </label>
              <pg-radio-toggle-select class="col-md-12 col-xs-12 no-margin no-padding" name="locationChangeInput" [(ngModel)]="Location"
                (selectedChanged)="onFilteringLocation($event)" [options]='locationOptions'>
              </pg-radio-toggle-select>
            </div>

            <pg-inputfield name="description" class="col-xs-12 col-sm-3 col-md-3 col-lg-3" [(ngModel)]="paramsModel.description"
                           displaytext="Name:"></pg-inputfield>
          </div>
        </div>

        <div>
          <button type="reset" class="btnReset" (click)="reset()">Reset</button>
          <button type="submit" name="btnSearch">Search</button>
        </div>
      </form>
    </div>

results.query TS

import {Component, OnInit, EventEmitter, Output} from '@angular/core';
import * as _ from 'lodash';
import { LocationService } from '../location-service.service';

@Component({
  selector: 'result-query',
  templateUrl: './result-query.component.html',
  styleUrls: ['./result-query.component.less'],
})
export class ResultQueryComponent implements OnInit {
  @Output() showResults:  EventEmitter<boolean> = new EventEmitter<boolean>();

  constructor(
      private LocationService: LocationService,
  ) {
    this.reset();
  }

  ngOnInit() {
    this.reset();
  }

  onSubmitClicked() {
    console.log('test')
  }

  reset(): void {
    console.log('I am the reset king');
    this.showResults = false;
    this.showResults.emit(true);
    this.onSubmitClicked();
  }
}

2 个答案:

答案 0 :(得分:0)

如果两个组件确实具有父子关系,则可以使用@Input()@Output()装饰器。

4 Ways to share data between angular components

Component Interaction

Input Output Example

父组件

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { Stephen } from '../stephen.model';

@Component({
    selector: 'app-parent',
    template: `

        Hello, Mr. (or Ms.): {{ selectedName }}

`,
styleUrls: ['./parent.component.css'],
    encapsulation: ViewEncapsulation.None
})

export class ParentComponent implements OnInit {
    stephen: Stephen;
    selectedName: string;

    constructor() {
        this.stephen = new Stephen();
        this.selectedName = this.stephen.firstName;
    }

    ngOnInit() {
    }

    updateName(selectedName: string): void {
    console.log('in parent');
    this.selectedName = selectedName;
    }

}

子组件

import { Component, OnInit, ViewEncapsulation, Input, Output, EventEmitter } from '@angular/core';
import { Stephen } from '../../stephen.model';
@Component({
    selector: 'app-child',
    template: `
        {{ stephen.firstName }}
        {{ stephen.lastName }}
        {{ stephen.fullName }}
        `,
    styleUrls: ['./child.component.css'],
    encapsulation: ViewEncapsulation.None
})
export class ChildComponent implements OnInit {
    @Input() stephen: Stephen;
    @Output() onNameSelected: EventEmitter;
    constructor() {
        this.onNameSelected = new EventEmitter();
    }
    ngOnInit() {
    }
    clicked(name: string): void {
        this.onNameSelected.emit(name);
    }
}

重要-第二个解决方案

但是在您的情况下,这两个组件似乎没有父子关系。如果要在两个组件之间共享数据,则可以创建一个可共享的服务。该服务将包含一个EventEmitter和一个EventEmitter,需要最新更改的组件将在ngOnInit方法中进行订阅,而拥有最新数据的组件将从此可共享服务中调用一个函数以发出该事件。

可共享的服务

import { Injectable, Output, EventEmitter } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class MessengerService {

  @Output() change: EventEmitter<any> = new EventEmitter();

  sendData(data: any): any {
    this.change.emit(data);
  }

}

想要了解此更改的组件将像这样在ngOnInit中订阅此事件。

messengerService.change.subscribe(emitedValue => {
   this.value = emitedValue;
});

具有新更改的组件将调用sendData方法为messenge /可共享服务,以便在需要时将新数据发布到事件订阅者。

答案 1 :(得分:0)

我不知道您是否忘记在问题中写它,但是您应该在results.Table HTML中包含一个results.query标记,并通过它调用输出。考虑到您的选择器是app-results-query,就像这样:

results.table HTML

<app-results-query (showResults)="changeShowResults($event)"></app-results-query>
<table *ngIf="showResults">
    //table stuff
</table>

results.table TS

showResults: boolean = true;

changeShowResults(event: boolean) {
    console.log('this is not getting called')
    if (event) {
      this.showResults = false;
    }
}