【发布时间】:2021-08-23 05:25:31
【问题描述】:
我正在尝试将值从一个组件传递到其他组件,到目前为止,我已经参考了一些 tuts 并创建了我的代码,但仍然面临问题。
我的 SelectComponent.ts 中有以下代码
export class SelectComponent implements OnInit {
user: LoginUser
selectLicences = [
{ name: 'Control', id: 1, isChecked: false, quantity: 1 },
{ name: 'Complete', id: 2, isChecked: false, quantity: 1 },
]
ControlQuantity=10
CompleteQuantity=20
我想在我的其他“buyerComponent”中访问 ControlQuantity 和 CompleteQuanitiy
这里是buyerComponent.ts
export class BuyerComponent implements OnInit, OnDestroy,AfterViewInit {
@ViewChild('selectProducts', { read: SelectComponent, static: false })
selectProducts: SelectComponent
CompleteQuantity:number
ControlQuantity:number
ngOnInit() {
this.CompleteQuantity=this.selectProducts.CompleteQuantity
this.ControlQuantity=this.selectProducts.ControlQuantitity
}
}
stackblitz 链接:https://stackblitz.com/edit/angular-ivy-umje3g?
【问题讨论】:
-
selectProducts是什么,组件之间有什么关系?请参考this video你会明白的 -
我添加了完整的 BuyerComponent
-
请也添加 HTML。
-
尝试在您的子组件上使用@Input。尽量避免使用
@ViewChild。它不适合单元测试 -
不要让你的一个组件侵入和访问另一个组件的内部事务。如果没有服务,更好的方法是拥有一个充当中介的父组件。组件 A 发出一个事件,该事件被监听并传递给组件 B。@Input 和 @output 是你的朋友。 angular.io/guide/inputs-outputs
标签: angular typescript