Gil*_*mes 2 angularjs angular2-directives angular
在Angular 1中,您可以使用&将函数作为参数传递给属性指令.我知道你可以使用函数将函数作为输入传递给Angular 2中的元素指令(组件)
<custom-component [callback]="myCallbackFuncton">
..etc
</custom-component>
Run Code Online (Sandbox Code Playgroud)
语法,但有没有办法只使用属性指令?我只能得到一个字符串(它允许我在范围内查看该函数),但更愿意一次性传递该函数.所以我希望能够在我的模板中写出这样的东西
<form custom-submit="ctrl.register">
...etc
</form>
Run Code Online (Sandbox Code Playgroud)
并在指令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();
});
}
}
Run Code Online (Sandbox Code Playgroud)
而不是必须写像
$scope.ctrl[$attrs.customSubmit]()
Run Code Online (Sandbox Code Playgroud)
Tie*_*han 10
试试这个:
@Output更好
使用@Output Plunk在线演示@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);
}
}
Run Code Online (Sandbox Code Playgroud)
应用程序/ 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';
}
}
Run Code Online (Sandbox Code Playgroud)
使用@Input Plunk在线演示@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();
}
}
Run Code Online (Sandbox Code Playgroud)
应用程序/ 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';
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6333 次 |
| 最近记录: |