Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
572 views
in Technique[技术] by (71.8m points)

angular - One way data binding in Angular2

I got the following html

<app-grid [columns]="columns" [data]="data" ></app-grid>

I want the data and columns properties to be immutable. The Grid should only show it. But in cases of sort or filtering the data would change, at least the order.

But here is my problem. If I access the data array and modify one property of an containing object. Like this.

this.data[0].name = "test"

The original gets changed. But I thought [data] is only one way data bound.

Could somebody point me in the right direction, to why this is happening and how I can omit it. I come from React where this would be pretty straight forward.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  • if you use [ngModel], [value], {{ param }} etc. you have one-way binding, model to view,
  • if you use (ngModelChange) you have one-way binding, view to model,
  • if you use [(ngModel)] you have two way binding.

But you are using a sub-component with the input @Input() property and this dances out of the line ;-) The notation is not what it looks like because it's always binded.

<sub-component [prop]="myObj"></sub-component>

So if you change the myObj in your sub-component, it will be binded:

ngOnInit() {
    this.myObj = this.myObj.push(this.newObj);
}

You could work with a local copy of myObj to prevent binding.

If you need an update from model you can push it with @Output() as Event:

<sub-component [prop]="myObj" (update)="myObj = $event"></sub-component>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...