我有孩子組件(日曆)和父組件(表單)。我必須在日曆中選擇值的值,我想訪問表單組件中的值。如何在angular2中獲取父組件的父組件值。最好的辦法是什麼?
我如何以最佳方式實現這一目標?
兒童Component.ts:如何從並實現
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);
}
:
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(){
}
}
父組件form2中的日期值在angular2中?
您可以使用共享服務或@ Input/@ Output屬性。後者在這種情況下是最好的,並且在Angular文檔中有詳細記錄:https:// angular。io/guide/component-interaction –
最好的方法是編寫一個可注入的服務來傳遞數據,方法是提供自定義組件的方式 – mast3rd3mon