Brett
Brett

Reputation: 1781

Angular 2 Polymer and a PaperChechboxSelectedDirective

I am trying to get Ng2 an Polymer to work together. To do so my objective is to create some Directives that listen to the paper-elements and converts the events or do whatever needs to be done to make angular understand the user interactions.

If I do this:

<paper-checkbox [checked]="bar" (change)="bar = $event.target.__data__.checked">
    Mark all as complete
</paper-checkbox>

I get bi-directional binding working with Ng2 (it's weird that I have to look into data to find the value of the checkbox though... any pointers on that one anyone ?).

So every thing work but I would like to cut on the ceremonies and have a Directive that get my 'bar' expression and sets it via the onChange Handler. Is this possible ?

The paper-checkbox directive

  @Directive({selector: 'paper-checkbox'})
  class PaperChechboxSelectedDirective {

    @Output() checkedChange:EventEmitter<any> = new EventEmitter();

    constructor(private element: ElementRef) {
      console.log('PaperChechboxSelectedDirective');
    }

    @HostListener('iron-change', ['$event'])
    onChange(e) {

    }
  }

Upvotes: 2

Views: 510

Answers (1)

yurzui
yurzui

Reputation: 214037

You can use two-way binding to do that like this:

@Directive({selector: 'paper-checkbox'})
class PaperChechboxSelectedDirective {
  @Input() checked: boolean;
  @Output() checkedChange:EventEmitter<any> = new EventEmitter();
  el: any;
  constructor(elRef: ElementRef) {
    this.el = elRef.nativeElement;
  }
  ngOnInit() {
     this.el.checked = this.checked;
  }
  @HostListener('iron-change', ['$event'])
  onChange(e) {
    this.checkedChange.emit(this.el.checked);
  }
}

and then on your template

<paper-checkbox [(checked)]="bar">
  Mark all as complete
</paper-checkbox>

See my working example here https://plnkr.co/edit/FzfNqxMNbVPxuwhf9Dbq?p=preview

Or without directive you can write a bit simple:

<paper-checkbox [checked]="bar" (change)="bar = $event.target.checked">
   Mark all as complete
</paper-checkbox>

Corresponding plunker here https://plnkr.co/edit/nVSdJGAwlXGEcHZXCOqV?p=preview

Upvotes: 3

Related Questions