在单击事件中,我试图在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;
}
......}
report-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:无法读取未定义的属性“ settDate”
不确定我们是否在这里丢失任何东西
最佳答案
无需在子组件上调用方法,您可以传递数据并将其绑定到Input setter。您需要在set
和Data
之间添加一个空格才能执行此操作
@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'
}
}
您可以在此处找到有效的堆叠闪电战:https://stackblitz.com/edit/angular-r24zqd