在子组件更改时将数据从ng-content传递到父组件

时间:2019-09-25 13:27:58

标签: angular angular8

更改子组件时需要将数据传递给父组件。

我有2个组件,当我从列表中选择某项时,我想将数据传递给父组件。

组件1- app-rx-search-field

<div>
  <form class="search_field_form_container">
    <input id="rx-search-field" type="search" class="form-control" name="search" placeholder="Search" [autocomplete]="false" [(ngModel)]="searchModel" [formControl]="searchFieldControl" />
    <ng-content></ng-content>
  </form>
</div>
import {Component, EventEmitter, OnInit, Output} from '@angular/core';
import {debounceTime, distinctUntilChanged} from 'rxjs/operators';
import {FormControl} from '@angular/forms';

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

  @Output() searchTermEvent: EventEmitter<string> = new EventEmitter<string>();

  public searchModel: any;
  public searchFieldControl = new FormControl();

  constructor() { }

  ngOnInit() {
    this.searchFieldControl.valueChanges
      .pipe(
        debounceTime(500),
        distinctUntilChanged()
      )
      .subscribe({
        next: value => {
          this.searchTermEvent.emit(value);
        }
      });
  }

}

组件2- app-rx-options

<div *ngFor="let option of optionsList">
  <p (click)="onClickOption($event, option)">{{option[key]}}</p>
</div>

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

@Component({
  selector: 'app-rx-options',
  templateUrl: './options.component.html',
  styleUrls: ['./options.component.styl']
})
export class OptionsComponent implements OnInit {

  @Input() optionsList: Array<any> = [];
  @Input() key?: string = '';
  @Output() optionSelected: EventEmitter<any> = new EventEmitter<any>();

  constructor() { }

  ngOnInit() {
  }

  public onClickOption = (event: MouseEvent, option: any) => {
    this.optionSelected.emit({event, option});
  }

}

这是这两个组件的实现方式:

<div>
  <app-rx-search-field (searchTermEvent)="onSearch($event)">
    <app-rx-options [optionsList]="suggestedSpecialtiesList$ | async" [key]="'specialty_name'" (optionSelected)="onOptionSelected($event)"></app-rx-options>
  </app-rx-search-field>
</div>

现在,当发出 optionSelected 事件时, rx-app-search-field 中的文本字段应显示该值。

0 个答案:

没有答案