Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
610 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 Reply

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...