试试这个:
@Output 更好
使用@Output Plunk online demo @Output
app/custom-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/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';
}
}
使用@Input Plunk online demo @Input()
app/custom-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/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';
}
}