Zaute
Zaute

Reputation: 95

Prevent changes to input values

We're developing an angular app (using Angular 5).

Our components typically has input and output parameters defined like this:

export class MultipleItemPickerComponent implements OnInit {
  @Input() itemPickerHeaderText: string;
  @Output() multipleItemsPickerOkClick: EventEmitter<string[]> = new EventEmitter();
  @Output() multipleItemsPickerCancelClick: EventEmitter<Event> = new EventEmitter();

In the corresponding template file, it is used like this:

<app-multiple-item-picker itemPickerHeaderText="{{question.texts['reason']}}" (multipleItemsPickerOkClick)="multipleReasonsPickerOkClick($event)" (multipleItemsPickerCancelClick)="multipleReasonsPickerCancelClick($event)"></app-multiple-item-picker>

And everything works just fine.

But in the same class it is possible to set the input value to something different than the original input value.

removeItemClick() {
    this.itemPickerHeaderText = "something completely different";
}

I want to prevent any changes to the input values. Is there any way to do this?

Upvotes: 1

Views: 461

Answers (1)

cyr_x
cyr_x

Reputation: 14257

You could mark the input property as readonly, the typescript compiler will prevent someone to update the input value inside the class from outside the constructor.

@Input() 
public readonly itemPickerHeaderText: string;

It's a little bit hacky but it should work in your case. Because the angular compiler won't complain about that it's read-only and the typescript compiler doesn't know about angular input bindings.

Upvotes: 4

Related Questions