0

I have a component A, which has custom directive on the page:

View:

<warning [details]='details'></warning>

Component:

    export class AComponent implements OnInit {
      details: ConfirmDetails = {
        header_class: ""   
      };
      languageChanged(newLang: string) {
        this.currentLanguage = newLang;
        this.ngOnInit();
      }
     ngOnInit() {
       if (this.currentLanguage === "English"){
          this.details.header_class = "line1 font50";
       }
       else{
         this.details.header_class = "line2 font90";
       }
    }

Once languageChanged() called, the directive is not updating.

    export class WarningComponent implements OnInit {
      @Input() details: ConfirmDetails;

      ngOnInit() {
           console.log(this.details.header_class);
       }
    }

So at the first page loading the details input is "line1 font50", but when languageChanged() called it does not change, so I dont see any console output.

I would appreciate any help.

Gyuzal
  • 1,581
  • 10
  • 52
  • 99
  • ngOnInit only execute when the "element" is attached to the DOOM (if you has, e.g. a *ngIf="toogle", each time toggle changes to true). But the variable really change. To test, add in your alert.html some like {{details}}, or use a setter https://stackoverflow.com/questions/36653678/angular2-input-to-a-property-with-get-set – Eliseo Jun 27 '19 at 13:50

1 Answers1

0

ngOnInit is called once when the component initialized for the first time. If you want to capture further changes to an @Input you need to use ngOnChanges hook. However, on complex types (object, array) ngOnChanges will be called if the object/array reference changes and it will not be called if a field of object changes or elements of array changes.

If you want changes to be captured on every call of languageChanged() do as follows;

in AComponent

  ngOnInit() {
    // clones the object with a brand new reference
    const tmpDetails = JSON.parse(JSON.stringify(this.details));
    if (this.currentLanguage === "English") {
      tmpDetails.header_class = "line1 font50";
    }
    else {
      tmpDetails.header_class = "line2 font90";
    }
    this.details = tmpDetails;
  }

in WarningComponent

export class WarningComponent implements OnChanges  {
  @Input() details: any;

  ngOnChanges() {
    console.log("details:", this.details);
  }
}

here is a working demo https://stackblitz.com/edit/angular-yhv8qq

ysf
  • 4,634
  • 3
  • 27
  • 29