调用服务方法的指令

时间:2019-04-15 16:57:29

标签: angular angular6 angular7

我在Angular 7中创建了模态服务,其用法如下Stackblitz Example

<button (click)="openModal()">Open Modal</button>

然后我在组件的代码中定义了openModal方法:

export class AppComponent  {

  constructor(private modalService: ModalService) { }

  openModal() {
    this.modalService.open({
      component: HelloComponent
    });
  }

}

是否可以创建一个指令来打开模式并像这样使用:

<button open-modal="HelloComponent">Open Modal</button>

不确定我要发布的语法...

2 个答案:

答案 0 :(得分:0)

您可以通过创建自定义指令来实现所需的行为:

open-modal.directive.ts

@Directive({
  selector: '[openModal]'
})
export class OpenModalDirective {
  @Input() modalIdentifier: string;

  constructor(private modalService: ModalService) { }

  @HostListener('click', ['$event'])
  clickEvent(event) {
    event.preventDefault();
    event.stopPropagation();
    this.modalService.openModal(this.modalIdentifier);
  }
}

虚拟 open-modal.service.ts

@Injectable({
  providedIn: 'root'
})
export class ModalService {

  constructor() {}

  openModal(modalIdentifier: string) {
    console.log(modalIdentifier)
  }
}

指令可以这样使用:

<button openModal [modalIdentifier]="'helloComponent'">Open Modal</button>

此示例为based on an article by Cory Rylanis available on StackBlitz

答案 1 :(得分:-1)

您可以直接调用方法,而不必使用指令。您可以保持简单。指令是在多个组件中使用的通用布局。

相关问题