TypeError: Cannot read property 'settDate' of undefined

TypeError: Cannot read property 'settDate' of undefined

在单击事件中,我试图将数据从一个组件传递到 Angular 中的另一个组件,我的组件如下所示

父组件

@Component({
  selector: 'app-reporting-filter',
  templateUrl: './reporting-filter.component.html',
  styleUrls: ['./reporting-filter.component.scss'],
  providers: [ProjectShipmentService]
})

export class ReportingFilterComponent implements DoCheck {

  @ViewChild(TjlShipdateFilterComponent, {static: false})
  private tjl: TjlShipdateFilterComponent;

  finalResult: ShipDateFilterModel[];

  click() {
    this.elem = this.getResultOnFilter(this.firstSelection, this.secondSelection);
      this.tjl.settDate(this.finalResult);
  }
   ........}

子组件就像

Component({
  selector: 'app-tjl-shipdate-filter',
  providers: [ProjectShipmentService],
  templateUrl: './tjl-shipdate-filter.component.html',
  styleUrls: ['./tjl-shipdate-filter.component.scss']
})
export class TjlShipdateFilterComponent implements DoCheck {
 tljShipDate: ShipDateFilterModel[];
  @Input() settDate(e: ShipDateFilterModel[]) {
    this.tljShipDate = e;
  }
......}

报告-filter.component.html

      <dxi-item  [ratio]="1">
              <dx-button (onClick)="click()" style="padding: 1vw 3vw 1.5vw 3vw; text-align: center; font-weight: bold;">Filter</dx-button>
      </dxi-item>

但是当按钮被点击时,'this.tjl.settDate(this.finalResult);'是在父组件中执行的。我得到:

TypeError: Cannot read property 'settDate' of undefined

不确定我们是否遗漏了什么

您可以传递数据并绑定到输入 setter,而不是调用子组件上的方法。您需要在 setData 之间添加一个 space 才能做到这一点

 @Input() set Data(e: ShipDateFilterModel[]) {
    this.tljShipDate = e;
  }

然后在父组件中你会想要创建一个可以向下传递的变量,例如


@Component({
  selector: 'app-reporting-filter',
  template: ` 
              <button (click)="click()">Click Me</button>
              <app-tjl-shipdate-filter [data]="tjlData" ></app-tjl-shipdate-filter>
  `,
  providers: [ProjectShipmentService]
})

export class ReportingFilterComponent {
  @ViewChild(TjlShipdateFilterComponent, {static: false})
  private tjl: TjlShipdateFilterComponent;
  private tjlData: any
  click() {
    this.tjlData = 'example data to pass'
  }
}

您可以在此处找到有效的 stackblitz:https://stackblitz.com/edit/angular-r24zqd