【问题标题】:How to get child component value to parent component in angular2. what is the best approach?如何在angular2中获取子组件值到父组件。什么是最好的方法?
【发布时间】:2017-08-08 08:30:31
【问题描述】:

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

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

子组件.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(){

  }
}

父组件:

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

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

【问题讨论】:

  • 您可以使用共享服务或@Input/@Output 属性。后者在这种情况下是最好的,它在 Angular 文档中有很好的记录:angular.io/guide/component-interaction
  • 最好的方法是编写一个可注入的服务来传递数据,因为提供的方式是为自定义组件提供的

标签: angular typescript


【解决方案1】:

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

在父组件中:

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

}

在子组件中

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

}

【讨论】:

    【解决方案2】:

    另一种解决方案:

    子组件:

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

    父组件:

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

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

    【讨论】:

      【解决方案3】:

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

      喜欢

      @ViewChild('minDateControl') calendar: Md2Datepicker;
      

      那么你就可以访问组件的所有公共资源了。

      【讨论】:

      • 父组件可以使用@ViewChild装饰器获取子组件中的元素吗?
      • 这是一个错误的解决方案,你不能使用@ViewChild从父组件访问子元素!!
      猜你喜欢
      • 2016-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多