指令中组件的调用方法

use*_*879 2 typescript angular2-directives angular

我定义了一个指令 iCheck,当我点击单选按钮时,我想调用一个组件中的方法......我的指令:directive.ts

declare var jQuery: any;

@Directive({
  selector: '[icheck]'
})

export class IcheckDirective implements AfterViewInit {
  constructor(private el: ElementRef) {
    jQuery(this.el.nativeElement).iCheck({
      checkboxClass: 'icheckbox_square-aero',
      radioClass: 'iradio_square-aero'
    }).on('ifChecked', function(event) {
      if (jQuery('input').attr('type') === 'radio') {
        // I want to call my method "selectType() of my component.ts ();
      }
    })
  }
  ngAfterViewInit(): void {
    return;
  }
}
Run Code Online (Sandbox Code Playgroud)

文件夹.component.ts

@Component({
  selector: 'app-folders',
  templateUrl: './folders.component.html',
  styleUrls: ['./folders.component.css']
})
export class FoldersComponent implements OnInit {

constructor(
    private route: ActivatedRoute,
    private router: Router)

   selectType(){ ==> Method that I want to call
    alert();
    console.log("Ici");
  }
..}
Run Code Online (Sandbox Code Playgroud)

我的 html 文件folder.component.html我在输入中使用我的指令

<input type="radio" icheck name="type" [(ngModel)]="type"value="OUT"> OUT
Run Code Online (Sandbox Code Playgroud)

那么当我单击单选按钮时如何调用方法“selectType()”?

Max*_*kyi 5

有两种方法可以做到这一点:

  1. 注入父组件实例,直接在其上调用方法
  2. 为指令定义输出事件并从父组件绑定到它。

注入父组件

export class IcheckDirective implements AfterViewInit {
  constructor(private el: ElementRef, private parentCmp: FoldersComponent) {
    const self = this;

    jQuery(this.el.nativeElement).iCheck({
        ...
    }).on('ifChecked', function(event) {
      if (jQuery('input').attr('type') === 'radio') {

        // I want to call my method "selectType() of my component.ts ();
        this.parentCmp.selectType('value');
      }
    })
Run Code Online (Sandbox Code Playgroud)

使用输出事件

为 定义输出IcheckDirective,然后从 绑定到它file.component

export class IcheckDirective implements AfterViewInit {

  @Output() callParentMethod = new EventEmitter();

  constructor(private el: ElementRef) {
    const self = this;

    jQuery(this.el.nativeElement).iCheck({
       ...
    }).on('ifChecked', function(event) {
      if (jQuery('input').attr('type') === 'radio') {

        // I want to call my method "selectType() of my component.ts ();
        self.callParentMethod.next('value');
      }
    })
  }
Run Code Online (Sandbox Code Playgroud)

然后在模板内部:

<input type="radio" icheck name="type" (callParentMethod)="selectType($event)"  [(ngModel)]="type"value="OUT"> OUT
Run Code Online (Sandbox Code Playgroud)