0
votes

I have a problem, that @input value in my angular app can not be updated

my code in child component

@Input() canAddMore?: boolean;

public setButtonVisible(){

this.canAddMore = false;
}

child component html

<button mat-mini-fab color="primary"
      (click)="setButtonVisible()" *ngIf="canAddMore">
      <mat-icon>add</mat-icon>
    </button>

this function will be called, if a input field in form is added

and in parent component

<app-field
                  
                  [canAddMore]="canAddMore"
                >
                </app-field>

in parent component there is also a button

public canAddMore: boolean;

public setButtonVisible(){

this.canAddMore = true;
}

and there is a button in parent component, which change the canAddMore = true.

the problem is, If I in child component setButtonVisible is called, and then call setButtonVisible in parent component,

the canAddMore will not be updated.

Any solutions?

2
Please find if this may help stackoverflow.com/questions/64333325/… - Obaid

2 Answers

0
votes

@Input's are immutable - you cannot change them. Instead of changing them, you can do this:

class TheComponent implements OnInit {

   @Input() immutableCanAddMore?: boolean;

   private mutableCanAddMore: boolean;

   ngOnInit() {
      this.mutableCanAddMore = immutableCanAddMore;
   }

   public setButtonVisible() {
     this.mutableCanAddMore = false;
   }

}
0
votes

You need to do following changes to update flag in your parent as well.

In your parent component HTML:

<app-field [(canAddMore)]="canAddMore"> </app-field>

In your child component TS :

@Input() canAddMore: boolean;
@Output() canAddMoreChange = new EventEmitter<boolean>();

public setButtonVisible(){
   this.canAddMore = false;
   this.canAddMoreChange.emit(this.canAddMore);
}