简体   繁体   English

如何访问和处理@ViewChildren?

[英]How to access and process @ViewChildren?

I have below hierarchy of components:我有以下组件层次结构:

product-list.component.ts产品列表.component.ts

<product-list>  

    <ng-content></ng-content>

</product-list>

product.component.ts产品.组件.ts

<product>   

    <ng-content></ng-content>

</product>

Demo.component.ts Demo.component.ts

       <product-list>

                <product>

                    <product-rating></product-rating>

                </product>

        </product-list>

        <button label="Submit" (click)="submit()"></button>

On Submit, I have to access product-rating component and depending on rating have to change the color of corresponding product component.在提交时,我必须访问产品评级组件,并且必须根据评级更改相应产品组件的颜色。 What is the best way to access and process this?访问和处理它的最佳方法是什么?

Demo.component.ts Demo.component.ts

@ViewChildren(ProductRatingComponent) ratings: QueryList<ProductRatingComponent>;

product.component.ts产品.组件.ts

@ViewChildren(ProductRatingComponent) ratings: QueryList<ProductRatingComponent>;

Is there any better way to access product-rating component?有没有更好的方法来访问产品评级组件?

Any help would be appreciated.任何帮助,将不胜感激。

Even though you have what looks like a relatively complex component structure, you can still achieve what you want to with standard @Output and @Input events and properties.即使您拥有看起来相对复杂的组件结构,您仍然可以使用标准的@Output@Input事件和属性来实现您想要的。

Your starting point is to decide which component is "controlling" everything.您的出发点是决定哪个组件“控制”一切。 In your case it's the demo component.在您的情况下,它是演示组件。 Demo component is deciding what the component hierarchy is.演示组件正在决定组件层次结构是什么。 Next you need to work out the desired flow of data.接下来,您需要计算出所需的数据流。 In your case, it will look a bit like this:在你的情况下,它看起来有点像这样:

product-rating -> demo -> product产品评级 -> 演示 -> 产品

A rating is determined by product-rating , and needs to get to product via the controller.评级由product-rating决定,需要通过控制器到达product

So you need to add an @Output event to product rating that the control can subscribe to:因此,您需要在控件可以订阅的产品评分中添加一个@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);
}

So now the demo component can handle the rating change events and send it to the product:所以现在演示组件可以处理评级更改事件并将其发送到产品:

demo.component.html演示.component.html

<product [rating]="rating">
  <product-rating (ratingChange)="onRatingChange($event)"></product-rating>
</product>

demo.component.ts演示.component.ts

rating: number;

onRatingChange(rating: number): void {
  this.rating = rating;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM