angular - 自 Parent Angular 2 起访问特定组件的方法

标签 angular directive

如何访问组件的方法:

我的指令.ts:

import { Parent } from '../../_common/Parent';
declare var jQuery: any;

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

export class IcheckDirective implements AfterViewInit {

  constructor(private el: ElementRef, private parentCmp: Parent) {
    jQuery(this.el.nativeElement).iCheck({
      checkboxClass: 'icheckbox_square-aero',
      radioClass: 'iradio_square-aero'
    }).on('ifChecked', function(event) {
      if (jQuery('input').attr('type') === 'radio') {
  // Here how can I call method **selectType** of the component FolderComponent when I check I radio button parentCmp.selectType(jQuery('input[name="filters.type"]:checked').val());
      }
    });
  }
}

我的Parent.ts

export abstract class Parent {
 }

我的 component.ts(使用 icheck)

import { Component, OnInit, ViewContainerRef } from '@angular/core';
    import { ActivatedRoute, Router } from '@angular/router';
    import { Parent } from '../../_common/Parent';

    declare var jQuery: any;

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

         name = 'FoldersComponent ';

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

      ngOnInit() {

      }

      selectType(value: string) {
         console.log(value);
      }
    }

在这里,我们可以看到我在FoldersComponent中有一个方法“selectType”,所以当我想在选中单选按钮时调用它

最佳答案

你可以这样做:

          if (jQuery('input').attr('type') === 'radio') {
             // Here how can I call method **selectType** of the component FolderComponent 
            //when I check I radio button parentCmp.selectType(jQuery('input[name="filters.type"]:checked').val());

             parentCmp.selectType();
          }

如果所有父组件都应具有 selectType 方法,则只需修改 Parent 类并添加该属性即可:

export abstract class Parent {
    selectType() {}
 }

如果有些 parent 不具备它,那么您可以像这样指定类型 any ,编译器不会生成错误:

constructor(private el: ElementRef, @Inject(Parent) private parentCmp:any ) {

关于angular - 自 Parent Angular 2 起访问特定组件的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44774805/

相关文章:

c# - C#中语句 "to qualify the use of a type in that namespace"是什么意思

angular - 在 Angular 6 中动态选择选项

javascript - 如何在 Angular 中删除双向数据绑定(bind) -2/4

angular - 从 Angular 中的模板引用变量中获取 ElementRef

javascript - 如何发布 angular2 指令

java - 如何使用自定义指令访问freemarker模板中的数据?

AngularJS/Karma - 指令中的单元测试功能

angular - 如何从 Angular 4 的下拉列表中预选一个值

angular - 找不到模块 './data.json' 。在 Angular

javascript - Angular Directive(指令)不会出现