0

I am using Angular 9 and I have this code:

app.component.html

<br><br>
<div class="container-fluid">
  <div class="row">
    <div class="col-md-12">

      <input #cmd />
      <button (click)="runCommand2(cmd.value)">runCommand</button>
      <br><br>


      RESULT: {{ output }}


    </div>
  </div>
</div>

Then in my app.component.ts

export class AppComponent {

  output: any;

  constructor(private myService: myService) {}

  runCommand2(command) {
    this.myService.executeShell2(command).subscribe(
      response => {
        if (response) { 
          this.output = response;
          console.log(this.output); // This appears in the console but does not appear in {{ output }} although the data is there
        }
      },
      error => {
        this.output = error;
      }
    );
  }

}

I also want to mention that for some reason if I call the method again, output will be populated on the view on the second time but not on the first time, although the data is there. Any ideas of what the problem could be?

joe2020wow
  • 237
  • 5
  • 12

1 Answers1

1

Not sure why the change detection isn't triggered the first time. Try to trigger it manually using detectChanges() method.

import { Component, ChangeDetectorRef } from '@angular/core';

export class AppComponent {
  output: any;

  constructor(private myService: myService, private changeDetectorRef: ChangeDetectorRef) { }

  runCommand2(command) {
    this.myService.executeShell2(command).pipe(take(1)).subscribe(     // <-- use `take(1)` to complete after one notification
      response => {
        if (response) { 
          this.output = response;
          console.log(this.output); // This appears in the console but does not appear in {{ output }} although the data is there
        }
      },
      error => {
        this.output = error;
      },
      () => {
        this.changeDetectorRef.detectChanges();    // <-- trigger change detection here
      }
    );
  }
}
ruth
  • 29,535
  • 4
  • 30
  • 57