从另一个组件访问组件属性

时间:2019-09-28 11:12:52

标签: angular

我对angular还是陌生的,试图实现一个自定义材质的datepicker组件(一个仅允许选择月份和年份的组件),并且在从单独的组件访问其值时遇到了麻烦。我修改了https://v7.material.angular.io/components/datepicker/overview中的一个示例,并尝试使用此特定stackoverflow帖子/答案中的建议:https://stackoverflow.com/a/50723598(Angular 7+部分)。

这是我的month-year-datepicker.component.html:

<mat-form-field class="reporting-datepicker">
  <input matInput [matDatepicker]="dp" [(ngModel)]="inputValue" (ngModelChange)="inputValueChange.emit(inputDPValue)" [min]="minDate">
  <mat-datepicker-toggle matSuffix [for]="dp"></mat-datepicker-toggle>
  <mat-datepicker #dp
                  [startView]="viewMode"
                  (yearSelected)="chosenYearHandler($event, dp)"
                  (monthSelected)="chosenMonthHandler($event, dp)"
                  panelClass="">
  </mat-datepicker>
</mat-form-field>

这是我的month-year-datepicker.component.ts(相关部分):

@Component({
  selector: 'month-year-datepicker',
  templateUrl: 'month-year-datepicker.component.html',
  styleUrls: ['month-year-datepicker.component.css'],
  providers: [
    {provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE]},
    {provide: MAT_DATE_FORMATS, useValue: MY_FORMATS}
  ],
})

export class MonthYearDatepicker {
  viewMode: string = "year";
  minDate: Moment;

  @Input() yearOnly: boolean = false;
  @Input() inputValue: Moment;
  @Output() inputValueChange: EventEmitter<Moment> = new EventEmitter<Moment>();

  constructor() {}

  ngOnInit() {
    if (this.yearOnly)
      this.viewMode = "multi-year"
    this.minDate = moment().subtract(5, 'months');
  }  

  chosenYearHandler(normalizedYear: Moment, datepicker: MatDatepicker<Moment>) {
    var ctrlValue = moment(this.inputValue);
    ctrlValue.year(normalizedYear.year());
    this.inputValue = ctrlValue;
    if (this.yearOnly) datepicker.close();
  }

  chosenMonthHandler(normalizedMonth: Moment, datepicker: MatDatepicker<Moment>) {
    var ctrlValue = moment(this.inputValue);
    ctrlValue.month(normalizedMonth.month());
    this.inputValue = ctrlValue;
    datepicker.close();
  }
}

然后,在我单独的report.component.html文件中,添加日期选择器,例如:

<month-year-datepicker [yearOnly]="false" [(inputValue)]="datepickerValue" ngDefaultControl></month-year-datepicker>

但是,在我单独的report.component.ts文件(简体)中,我无法访问datepickerValue的值:

export class ReportingComponent extends ComponentBase implements OnInit, OnDestroy {

  datepickerValue: Date;

  constructor() {}
  ngOnInit(){}

  getDate() {
    return this.datepickerValue; // <- this is undefined still
  }      

}

我显然丢失了一些东西或误解了组件之间的绑定如何工作,将不胜感激!谢谢!

1 个答案:

答案 0 :(得分:0)

更新

(ngModelChange)="inputValueChange.emit(inputDPValue)"

(ngModelChange)="inputValueChange.emit($event)"

也请将此错字[(ngModel)]="inputValue"更新为[ngModel]="inputValue",因为您已经在使用(ngModelChange)语法。不太可能破坏任何内容,但是您应该使用一种或另一种语法,不能同时使用两种语法。