首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何访问和处理@ViewChildren?

如何访问和处理@ViewChildren?
EN

Stack Overflow用户
提问于 2020-02-05 07:22:27
回答 1查看 40关注 0票数 0

组件的层次结构如下:

product-list.component.ts

代码语言:javascript
复制
<product-list>  

    <ng-content></ng-content>

</product-list>

product.component.ts

代码语言:javascript
复制
<product>   

    <ng-content></ng-content>

</product>

Demo.component.ts

代码语言:javascript
复制
       <product-list>

                <product>

                    <product-rating></product-rating>

                </product>

        </product-list>

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

在提交时,我必须访问product-rating组件,并根据评级更改相应的产品组件的颜色。访问和处理这个问题的最佳方法是什么?

Demo.component.ts

代码语言:javascript
复制
@ViewChildren(ProductRatingComponent) ratings: QueryList<ProductRatingComponent>;

product.component.ts

代码语言:javascript
复制
@ViewChildren(ProductRatingComponent) ratings: QueryList<ProductRatingComponent>;

是否有更好的方法来访问product-rating组件?

任何帮助都将不胜感激。

EN

回答 1

Stack Overflow用户

发布于 2020-02-15 17:25:06

即使您有一个看起来比较复杂的组件结构,您仍然可以使用标准的@Output@Input事件和属性实现您想要的结果。

您的出发点是决定哪个组件是“控制”一切。在您的例子中,它是演示组件。演示组件正在决定组件层次结构是什么。接下来,您需要计算出所需的数据流。在您的例子中,它看起来有点像这样:

产品评级->演示->产品

评级由product-rating确定,需要通过控制器到达product

因此,您需要向控件可以订阅的产品评级添加一个@Output事件:

代码语言:javascript
复制
@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

代码语言:javascript
复制
<product [rating]="rating">
  <product-rating (ratingChange)="onRatingChange($event)"></product-rating>
</product>

demo.component.ts

代码语言:javascript
复制
rating: number;

onRatingChange(rating: number): void {
  this.rating = rating;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60070779

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档