组件的层次结构如下:
product-list.component.ts
<product-list>
<ng-content></ng-content>
</product-list>product.component.ts
<product>
<ng-content></ng-content>
</product>Demo.component.ts
<product-list>
<product>
<product-rating></product-rating>
</product>
</product-list>
<button label="Submit" (click)="submit()"></button>在提交时,我必须访问product-rating组件,并根据评级更改相应的产品组件的颜色。访问和处理这个问题的最佳方法是什么?
Demo.component.ts
@ViewChildren(ProductRatingComponent) ratings: QueryList<ProductRatingComponent>;product.component.ts
@ViewChildren(ProductRatingComponent) ratings: QueryList<ProductRatingComponent>;是否有更好的方法来访问product-rating组件?
任何帮助都将不胜感激。
发布于 2020-02-15 17:25:06
即使您有一个看起来比较复杂的组件结构,您仍然可以使用标准的@Output和@Input事件和属性实现您想要的结果。
您的出发点是决定哪个组件是“控制”一切。在您的例子中,它是演示组件。演示组件正在决定组件层次结构是什么。接下来,您需要计算出所需的数据流。在您的例子中,它看起来有点像这样:
产品评级->演示->产品
评级由product-rating确定,需要通过控制器到达product。
因此,您需要向控件可以订阅的产品评级添加一个@Output事件:
@Output() ratingChange: EventEmitter<number> = new EventEmitter<number>();
// this is some event handler that handles the user-driven rating change
onRatingChange(): void {
// Emit the rating. I am guessing here that the rating is stored in some property
// It might come into this function as an event arg - that's up to your design.
this.ratingChange.emit(this.rating);
}因此,现在演示组件可以处理评级更改事件,并将其发送到产品:
demo.component.html
<product [rating]="rating">
<product-rating (ratingChange)="onRatingChange($event)"></product-rating>
</product>demo.component.ts
rating: number;
onRatingChange(rating: number): void {
this.rating = rating;
}https://stackoverflow.com/questions/60070779
复制相似问题