简体   繁体   中英

Pass boolean to another Angular component

I have two Angular components

results.table and results.query

I want to hide the table inside the results.table.component when the user clicks on the reset button within the results.query.component

Maybe I am doing this wrong with event emitter, or maybe there is a better way to do this

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

If two components does have a parent child relationship, you can use @Input() @Output() decorators.

4 Ways to share data between angular components

Component Interaction

Input Output Example

Parent Component

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

}

Child Component

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

Important - second solution

But in your case these 2 components don't seem to have a parent child relationship. If you want to share data between two components, you can create a share-able service. This service will contain and EventEmitter to which a component that needs latest change will subscribe in ngOnInit method and the component which will have latest data will call a function from this share-able service to emit that event.

share-able service

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

}

The component that want to know about this change will subscribe to this event in it the ngOnInit like this.

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

The component that has the new change will call the sendData method is messenge / share-able service to post new data to the event subscribers whenever it is required.

I dont know if you forgot to write it in your question, but you should have a results.query Tag in your results.Table HTML, and call the output through it. Considering your selector is app-results-query, it would be like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM