从Parent Angular 2开始,访问特定Component的方法

时间:2017-06-27 07:44:41

标签: angular directive

如何访问组件的方法:

my 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”,所以当我想在我选中单选按钮时调用它

1 个答案:

答案 0 :(得分:2)

你可以这样做:

selectType

如果所有父组件都应该有Parent方法,那么只需修改export abstract class Parent { selectType() {} } 类并添加该属性:

any

如果某些家长不会拥有它,那么您可以像这样指定类型constructor(private el: ElementRef, @Inject(Parent) private parentCmp:any ) { ,编译器不会生成错误:

python prediction/run.py \
--runner DataflowRunner \
--project $PROJECT \
--staging_location $BUCKET/staging \
--temp_location $BUCKET/temp \
--job_name $PROJECT-prediction-bq \
--setup_file prediction/setup.py \
--model $BUCKET/model \
--source bq \
--input $PROJECT:mnist.images \
--output $PROJECT:mnist.predict