0

Maybe I miss something simple, but it made me a headache.

When the user clicks a button I'm trying to create a ModifyQuestionComponent inside a wrapper component.

That ModifyQuestionComponent is registered to listen to an event:

export class ModifyQuestionComponent implements OnInit {
  private graphService: GraphService;
  question: Question = new Question();

  constructor(graphService: GraphService) {
    this.graphService = graphService;
  }

  ngOnInit() {
    // @@@@@ here listen to update for the question
    this.graphService.questionSelected.subscribe((question) => {

      this.question = question;
    });
  }
}

The HTML of this component has a form which shows all values of the question attribute as follows:

<div class="form-group has-float-label input-group-sm">
  <input type="text" class="form-control"
         placeholder="What is the question id?"
         required
         [(ngModel)]="question.id" // @@@ here
         name="id">
  <label for="id">Id</label>
</div>

Now, when I click the button I fire two events: one to the wrapper component to instantiate this ModifyQuestionComponent inside it, and another event to the ModifyQuestionComponent to change its question property content.

this.changedSelected.next('question'); // for wrapper component to instatiate ModifyQuestionComponent 
this.questionSelected.next(question); // fot ModifyQuestionComponent to display the question

The problem is that the second event is not received and ModifyQuestionComponent get's created but doesn't receive the event to populate the form. If I press one more time the button, the form gets populated. I suppose that is because it is fired while instantiating the component?

How to solve it?

Z. Bagley
  • 8,942
  • 1
  • 40
  • 52
Andrei Margeloiu
  • 849
  • 2
  • 12
  • 17

1 Answers1

0

Problem solved; I needed to use a BehaviousSubject instead of a Subject.

The main difference is that a BehaviourSubject is initialized with a default value, and when someone subscribes to it, it returns the last set value.

Read more about BehaviourSubject: https://stackoverflow.com/a/40231605/7298086

Andrei Margeloiu
  • 849
  • 2
  • 12
  • 17