使用@viewchild访问多个viewchildren [重复2]

时间:2020-01-27 23:03:52

标签: html angular typescript angular-components

我在Angular 8的父组件html中的for循环中使用<app-comment #cmp></app-comment>生成了几个子组件。这很好用。但是现在,当我在一个子组件中更改某些内容时,它会在所有子组件中更改它。如何仅访问一个子组件?我尝试了以下给出的答案:https://stackoverflow.com/questions/32693061/how-can-i-select-an-element-in-a-component-templateenter link description here 但是没有成功:(

console.log("my comment components: ", this.components.toArray());} 总是在控制台中打印出一个空数组:

my comment components: [] length: 0 <prototype>: Array []

我的目标是,能够在一个子组件中添加注释,而不必同时在其他子组件中添加注释:

How my application looks right now

--- the html of the parent component ---   

<agm-marker *ngFor="let post of posts">
<agm-info-window>  
<!-- some unrelevant code that adds the title "Best restaurant" etc -->  
<!-- the child component for adding and displaying comments: -->
   <app-comment #cmp></app-comment>
</agm-info-window>
</agm-marker>

--- the typescript of the parent component ---

export class MapComponent implements OnInit {

/** Get handle on cmp tags in the template */
@ViewChildren('cmp', { read: ElementRef }) components:QueryList<CommentComponent>;

ngAfterViewInit(){
// print array of CustomComponent objects
console.log("my comment components: ", this.components.toArray());}


--- the html of the child component ---

<div class="d-flex justify-content-center">
<input #comment placeholder="comment" />
<div class="d-flex justify-content-center">
    <button (click)="addComment(comment.value)">Comment</button>
</div>    
</div>

<div *ngFor="let comment of comments">
   <p>{{ comment.text }} </p>
   <p>by {{ comment.user.userName }}</p>
</div>

0 个答案:

没有答案