Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Binding Component to multiple values

I'm trying to implement a date range selector in Angular 2.

I already have a working widget, which I have to link to the @angular/forms subsystem.

What I would like is to be able to bind the two output values (let's say rangeStart and rangeEnd) to two distinct properties in the containing form's state.

Is there a way I can configure the NgModel settings to accomplish this?

An alternative could be to bind a single property of type DateRange:

type DateRange = {
    from: Date,
    to: Date
};

buyt I don't know if this is even possible.

Any suggestion on how to accomplish this?

Edit:

What I have is a jQuery-derived, JS component which exposes an onChange, like so:

component.on('change', (eventData) => {
  // here I have eventData.from and eventData.to as Date values
});

I want to integrate this kind of handler in a Angular friendly component. But, I can't simply do this:

<my-date-range-picker name"xyz" [(NgModel)]="aDateRangeValue"></my-date-range-picker>

Because, AFAICT, change detection is not going to work with composite values. What should I expose in my component? Two EventEmitters? Can I leverage NgModel in some way?

like image 931
A. Chiesa Avatar asked Jun 05 '26 11:06

A. Chiesa


1 Answers

If you want to create you own ngModel like two-way data-binding, that's what you should do:

@Component()
export class MyComponent {

      myValue = 0;

      @Output()
      myValueChange = new EventEmitter();

      @Input()
      get myValue() {
             return this.myValue;
      }

      set myValue(val) {
           this.myValue= val;
           this.myValueChange.emit(this.myValue);
      }
}

Now you can use it as follows and have two-way data binding in effect:

<my-component [(myValue)]="someExpression"></my-component>

Adding a link to a simple tutorial on this as well: http://www.angulartraining.com/blog/tutorial-create-your-own-two-way-data-binding-in-angular/

like image 96
alcfeoh Avatar answered Jun 07 '26 23:06

alcfeoh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!