typescript 如何在angular2中获取子组件值到父组件。最好的方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45563205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:48:03  来源:igfitidea点击:

How to get child component value to parent component in angular2. what is the best approach?

angulartypescript

提问by VSK

I have child component (calendar) and parent component (form). I have to select value in calendar and I want to access value in form component.

我有子组件(日历)和父组件(表单)。我必须在日历中选择值,我想访问表单组件中的值。

How can I achieve this in best possible way?

我怎样才能以最好的方式实现这一目标?

Child Component.ts:

子组件.ts:

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

@Component({
  selector: 'calendar',
  template: '
    <md2-datepicker name="mindate"
                      placeholder="Minimum Date"
                      [(ngModel)]="minDate"
                      [mode]="mode"
                      [touchUi]="touch"
                      [format]="dateFormat"
                      #minDateControl="ngModel" [fromDate]="minDateControl"></md2-datepicker>
      <md2-datepicker name="maxdate"
                      placeholder="Maximum Date"
                      [(ngModel)]="maxDate"
                      [min]="minDate"
                      [mode]="mode"
                      [touchUi]="touch"
                      [format]="dateFormat"
                      #maxDateControl="ngModel"></md2-datepicker>
  ',
})

export class CalendarComponent implements OnInit {

  today: Date = new Date();


  minDate: Date;
  maxDate: Date;

  constructor(){

  }

  ngOnInit(){

  }
}

Parent component :

父组件:

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

import { Router } from '@angular/router';

import { ChartModule,ChartComponent } from 'angular2-chartjs';
import { ChartService } from './../shared/chart.service';

import { Colors, xAxisWidth } from './../shared/data';

@Component({
  selector: 'form-js',
  template: `
    <h3 class="chartHeading">Parameter Selection Form</h3>
    <calendar></calendar>
  `,
})

export class FormComponent implements OnInit {


  @Input fromDate: string;
  @Input toDate: string;

  constructor(){

  }

  ngOnInit(){

  }

  alert(fromDate);
}

How can I achieve from and to date values in form component in angular2?

如何在 angular2 的表单组件中实现起始和截止日期值?

回答by Raed Khalaf

you can use the @Outputdecorator, which makes it easy to communicate between the Parent component and the Child component

您可以使用@Output装饰器,它可以轻松地在 Parent 组件和 Child 组件之间进行通信

in the Parent component:

在父组件中:

@Component({
  selector: 'form-js',
  template: `
    <h3 class="chartHeading">Parameter Selection Form</h3>
    <calendar (onSelectValue)='selectValue($event)'></calendar>
  `,
})
export class FormComponent{

   selectValue( newValue : any ) {
     console.log(newValue);
   }

}

in the child component

在子组件中

import {
  Component,
  OnInit,
  ViewChild,
  Input,
  Output  // add this import
  EventEmitter // add this import as well
} from '@angular/core';

@Component({
  selector: 'calendar',
  template: '
    <md2-datepicker name="mindate"
                      placeholder="Minimum Date"
                      [(ngModel)]="minDate"
                      [mode]="mode"
                      (change)='onChange()'  // add this event listener
                      [touchUi]="touch"
                      [format]="dateFormat"
                      #minDateControl="ngModel" [fromDate]="minDateControl"></md2-datepicker>
      <md2-datepicker name="maxdate"
                      placeholder="Maximum Date"
                      [(ngModel)]="maxDate"
                      [min]="minDate"
                      (change)='onChange()'  //add this event listener
                      [mode]="mode"
                      [touchUi]="touch"
                      [format]="dateFormat"
                      #maxDateControl="ngModel"></md2-datepicker>
  ',
})

export class CalendarComponent implements OnInit {
  //declare this EventListener in order to listen on it in the parent component.
  @Output() onSelectValue = new EventEmitter<{minDate: Date , maxDate: Date}>();
  today: Date = new Date();


  minDate: Date;
  maxDate: Date;

  constructor(){

  }

  ngOnInit(){

  }

  onChange() {
     this.onSelectValue.emit( {minDate: this.minDate, maxDate:this.maxDate} );
  }

}

回答by VSK

Another solution:

另一种解决方案:

Child Component:

子组件:

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

@Component({
  selector: 'calendar',
  template: `
    <md2-datepicker name="mindate"
                      placeholder="Minimum Date"
                      [(ngModel)]="minDate"
                      [mode]="mode"
                      [touchUi]="touch"
                      [format]="dateFormat"
                      #minDateControl="ngModel"></md2-datepicker>
      <md2-datepicker name="maxdate"
                      placeholder="Maximum Date"
                      [(ngModel)]="maxDate"
                      [min]="minDate"
                      [mode]="mode"
                      [touchUi]="touch"
                      [format]="dateFormat"
                      #maxDateControl="ngModel"></md2-datepicker>
  `,
})

export class CalendarComponent implements OnInit {

  minDate: Date;
  maxDate: Date;

  constructor(){

  }

  ngOnInit(){

  }

}

Parent component :

父组件:

import {
  Component,
  OnInit,
  ViewChild,
  Input,
  ElementRef
} from '@angular/core';

import { Router } from '@angular/router';

import { ChartModule,ChartComponent } from 'angular2-chartjs';
import { ChartService } from './../shared/chart.service';

import { Colors, xAxisWidth } from './../shared/data';

@Component({
  selector: 'form-js',
  template: `
    <h3 class="chartHeading">Parameter Selection Form</h3>
    <calendar #test></calendar>
    <button (click)="showAlert();"></button>
  `,
})

export class FormComponent implements OnInit {

  @ViewChild('test') calendar;

  constructor(){

  }

  ngOnInit(){

  }

  showAlert(){
    alert(this.calendar.minDate);
  }

}

Now i have access of ngModel properties in showAlert() method

现在我可以在 showAlert() 方法中访问 ngModel 属性

回答by Peter777

If you want to get value of a child Component in the Parent Component you can simply use @ViewChildannotation.

如果你想在父组件中获取子组件的值,你可以简单地使用@ViewChild注解。

like

喜欢

@ViewChild('minDateControl') calendar: Md2Datepicker;

Then you have access to all the public resources of the component.

然后您就可以访问该组件的所有公共资源。