CheapSteaks
CheapSteaks

Reputation: 5011

One-time (not one-way) binding for @Inputs in angular2?

In angular 1.x, one-way databinding syntax was ::

I'm trying to pass an object down to a child component with one-time binding. The child needs to get the initial data from the parent, but the parent doesn't ever change the data and doesn't need to know if the child changed it.

<parent [child-data]="childData"/>

How can I one-time bind this?

Upvotes: 6

Views: 4896

Answers (3)

Igor
Igor

Reputation: 550

I had the same problem. In my case was enough to add an additional Input() set and save the new value only if the old one wasn't set yet

 @Input() set initChildData(initChildData: any) {
        if (initChildData && this.childData == undefined) {
            this.childData = initChildData;
        }
    }

Then in html just call [initChildData] instead of [child-data] You can use it in one component for one Input or just move it to an abstract BaseComponent class to make it more generic

Upvotes: 0

dalvarezmartinez1
dalvarezmartinez1

Reputation: 1405

I know this is old, but I stumbled upon this: ANGULAR CHANGE DETECTION EXPLAINED which basically says that as long as you use immutable inputs and observables (which might not be the case all the time, but it could be in some big tables with lots of bindings):

  • ChangeDetectionStrategy.OnPush on the component will make this whole component rerender only when some of the @Input references change (from inside or outside the component). Or there is some event from inside the template of this component. Check this plunkr I made: ChangeDetectionStrategy.OnPush change to default, and try the buttons again, see how many times the binding is called. If you never change the @Input, then you got One time binding yeah I know it's for the whole component, not just for specific bindings though....
  • If you have data which changes without its reference changing, inject the ChangeDetectorRef and call markForCheck when the change happens.

Upvotes: 1

Clement
Clement

Reputation: 4058

This post: angular 2 one time binding seams to indicate the using ChangeDetectionStrategy.CheckOnce could be the solution.

Upvotes: 1

Related Questions