如何将数据从子级传递到父级组件Angular [英] How to Pass data from child to parent component Angular

查看:205
本文介绍了如何将数据从子级传递到父级组件Angular的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为search_detail的组件,该组件中还有一个名为Calendar的组件

I have a component named search_detail which has another component inside it named calendar,

SearchDetail_component.html

 <li class="date">
   <div class="btn-group dropdown" [class.open]="DatedropdownOpened">
   <button type="button" (click)="DatedropdownOpened = !DatedropdownOpened"   class="btn btn-default dropdown-toggle" data-toggle="dropdown"
aria-haspopup="true" [attr.aria-expanded]="dropdownOpened ? 'true': 'false'">
      Date <span class="caret"></span>
  </button>
  <ul class="dropdown-menu default-dropdown">
     <calendar  ></calendar>
     <button > Cancel </button>
     <button (click)="setDate(category)"> Ok </button>
   </ul>                            
 </div>
</li>

SearchDetail_component.ts

import 'rxjs/add/observable/fromEvent';
@Component({
    selector: 'searchDetail',
    templateUrl: './search_detail.component.html',
    moduleId: module.id

})

Calendar.component.ts

import { Component, Input} from '@angular/core'; 
@Component({
    moduleId:module.id,
    selector: 'calendar',
    templateUrl: './calendar.component.html'
})

    export class CalendarComponent{
      public fromDate:Date = new Date();    
      private toDate:Date = new Date();
      private events:Array<any>;
      private tomorrow:Date;
      private afterTomorrow:Date;
      private formats:Array<string> = ['DD-MM-YYYY', 'YYYY/MM/DD', 'DD.MM.YYYY', 'shortDate'];
      private format = this.formats[0];
      private dateOptions:any = {
        formatYear: 'YY',
        startingDay: 1
      };
      private opened:boolean = false;

      public getDate():number {
        return this.fromDate.getDate()  || new Date().getTime();
      }
    }

我想单击搜索详细信息页面中的确定"按钮来访问开始日期和结束日期.我该怎么办?

I want to access the startdate and enddate on click of the ok button in the search detail page. how can i do?

推荐答案

在子组件中将EventEmitter注册为@Output:

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

发出点击价值:

public pickDate(date: any): void {
    this.onDatePicked.emit(date);
}

收听父组件模板中的事件:

Listen for the events in your parent component's template:

<div>
    <calendar (onDatePicked)="doSomething($event)"></calendar>
</div>

并在父组件中:

public doSomething(date: any):void {
    console.log('Picked date: ', date);
}

在官方文档中也对此进行了很好的解释:组件交互.

It's also well explained in the official docs: Component interaction.

这篇关于如何将数据从子级传递到父级组件Angular的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆