有没有办法将Angular 2属性指令传递给函数

时间:2017-02-03 11:33:02

标签: angularjs angular angular2-directives

在Angular 1中,您可以使用&将函数作为参数传递给属性指令。我知道你可以使用

将函数作为输入传递给Angular 2中的元素指令(组件)
<custom-component [callback]="myCallbackFuncton">
..etc
</custom-component>

语法,但有没有办法只使用属性指令?我只能得到一个字符串(它允许我在范围内查看该函数)但更喜欢一次性传递该函数。 所以我希望能够在我的模板中写出类似的内容

 <form custom-submit="ctrl.register">
 ...etc
 </form>

并在指令js中,

@Directive({
    selector: '[custom-submit]',
})
@Inject('$element', '$attrs')

export default class CustomSubmit {
    constructor($element, $scope, $attrs) {
        this.$element = $element;

        $element[0].addEventListener('submit', () => {
          // custom validation behaviour
          $attrs.customSubmit();
        });
   }
}

而不必写像

这样的东西
 $scope.ctrl[$attrs.customSubmit]()

1 个答案:

答案 0 :(得分:9)

试试这个:

@Output更好

使用@Output Plunk online demo @Output

应用/定制submit.directive.ts

import { Directive, Output, HostListener, EventEmitter } from '@angular/core';


@Directive({
  selector: '[custom-submit]'
})
export class CustomSubmit {
  constructor(
    // ...
  ) { }

  @Output('custom-submit') customSubmit: EventEmitter<any> = new EventEmitter();

  @HostListener('submit', ['$event'])
  onSubmit(e) {
    e.preventDefault();
    console.log('call this');
    this.customSubmit.emit(e);
  }
}

应用/ app.component.ts

import {Component} from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <form (custom-submit)="onSubmit($event)">
      <div *ngFor="let item of [1,2,3,4,5,6]">
        {{item}}
      </div>
      <button type="submit">Submit</button>
      <p>Status {{ message }}</p>
    </form>
  `
})
export class AppComponent {
  message: string = '';

  onSubmit(e) {
    console.log(e);
    this.message = 'submitted';
  }
}

USE @Input Plunk online demo @Input()

应用/定制submit.directive.ts

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

@Directive({
  selector: '[custom-submit]'
})
export class CustomSubmit {
  constructor(
    // ...
  ) { }

  @Input('custom-submit') customSubmit: Fn;

  @HostListener('submit', ['$event'])
  onSubmit(e) {
    e.preventDefault();
    console.log('call this');
    this.customSubmit();
  }
}

应用/ app.component.ts

import {Component} from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <form [custom-submit]="onSubmit">
      <div *ngFor="let item of [1,2,3,4,5,6]">
        {{item}}
      </div>
      <button type="submit">Submit</button>
      <p>Status {{ message }}</p>
    </form>
  `
})
export class AppComponent {
  message: string = '';
  constructor() {
    // be careful when pass method to other Component Input
    this.onSubmit = this.onSubmit.bind(this);
  }
  onSubmit() {
    console.log('submitted');
    this.message = 'submitted';
  }
}