Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - How does the directive give data to the host?

I have what I think should be a pretty simply problem to solve in Angular 2, but I just can't find the right syntax.

My goal is a directive that does the following:

  1. Accepts arbitrary data as value. E.g., [my-data]="[1,2,3,4,5]"
  2. Processes this on change. E.g. onChange() { return this.data.length = 55; }.
  3. Sends this data to the host, and binds to a host property.

I'm fine on 1), but a little lost on 2) and 3). So far I have something like:

@Directive({
  selector: ['ap-data'],
  host: {
    '(change)': 'onChange()'
  }
})
export class DataDirective {

  @Input('ap-data') data: any;

  @HostBinding('attr.ap-data') get dataSet() {
    return processData(this.data);
  }

  ...

}

@Component({
  selector: 'myComponent',
  directive: [DataDirective],
  template: `
   <div [ap-data]="[1,2,3,4,5]"></div>
  `
})
export class MyComponent {

  public data: any[];

  public dataSet: ProcessedDataType;

  ...

}
like image 322
Jefftopia Avatar asked Dec 04 '25 15:12

Jefftopia


1 Answers

For directive to host binding use an EventEmitter:

@Output('ap-data-change') apDataChange: EventEmitter = new EventEmitter() 

onChange() {
  ... 
  this.apDataChange.next(someValue);
} 

<div [ap-data]="[1,2,3,4,5]" (ap-data-change)=hostField=event$></div>
like image 157
Günter Zöchbauer Avatar answered Dec 06 '25 06:12

Günter Zöchbauer