web-dave / angular-starter-v2

6 stars 3 forks source link

Create a Directive #14

Open web-dave opened 7 years ago

web-dave commented 7 years ago
web-dave commented 7 years ago

generate

  ng g d books/shared/order-btn
web-dave commented 7 years ago

order-btn.directive.ts


import { Directive, Input, ElementRef, OnChanges, HostListener } from '@angular/core';

@Directive({
  selector: '[orderBtn]'
})
export class OrderBtnDirective implements OnChanges {
  orderBtnElement: HTMLButtonElement = document.createElement('button');

  @Input() orderBtn;

  ngOnChanges(changeObj) {

    this.orderBtnElement.innerText = this.orderBtn;
  }

  @HostListener('mouseenter') onMouseEnter() {
    console.log('mouseenter');
  }

  @HostListener('mouseleave') onMouseLeave() {
    console.log('mouseleave');
  }

  constructor(private elementRef: ElementRef) {
    elementRef.nativeElement.appendChild(this.orderBtnElement);
    this.orderBtnElement.onclick = () => {
      console.log('this.orderBtn:', this.orderBtn)
    }
  }

}
web-dave commented 7 years ago

book-details.component.html

  <div class="panel-body" orderBtn="Buy me!!">
    ...
 </div>
web-dave commented 6 years ago

<div class="panel-body" [orderBtn]="book">
    ...
 </div>