r3plica
r3plica

Reputation: 13397

Angular detect changes in child component

I asked a question: Angular controlling a list of objects visibility on the same view which was answered but has raised another question.

If I have a child component, how can I get it to know when something has changed. Here is a link to some example code:

https://stackblitz.com/edit/angular-e72hx9?file=src%2Fapp%2Fanswers%2Fanswers.component.ts

I have tried to use OnChanges on the AnswerComponent. I was hoping that when I changeda property within the object array, OnChanges would fire and then update my list, but it doesn't. I assume this is an easy thing, but I am unsure how to do it.

Can anyone help?

Upvotes: 0

Views: 4913

Answers (1)

freepowder
freepowder

Reputation: 417

You can probably use @Output and only one questions collection.

In app.component template

<app-questions [questions]="questions" (setActive)="setActive($event)"></app-questions>
<app-answers [questions]="questions"></app-answers>

In app.component class

setActive(item) {
  this.questions.map(question => {
    if(question.text === item.text) {
      question.active = !question.active;
    }
 });

}

The answer component

export class AnswersComponent {
  @Input() questions: Question[]
  constructor() { }
}

The answer template

 <h2>Answers</h2>
 <div *ngIf="questions">
   <div *ngFor="let question of questions">
      {{ question.active }} <!-- check how this will change true/false -->
     <ul>
       <li *ngFor="let answer of question.answers">{{ answer.text }}</li>
     </ul>

The question component

export class QuestionsComponent {
 @Input() questions: Question[]
 @Output() setActive = new EventEmitter();
}

The question template

<h1>Questions</h1>
<ul>
  <li *ngFor="let question of questions"><button (click)="setActive.emit(question)">{{ question.text }}</button> (active: {{ question.active }})</li>
</ul>

Hope that will help!

https://stackblitz.com/edit/angular-mq48s2

Upvotes: 3

Related Questions