试试这个:
@Output is better
使用@OutputPlunk 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';
}
}
使用@inputPlunk 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';
}
}
感谢您的答复 - 我得到与此相同的结果 - 输入作为字符串传递,而不是对函数的引用 –
'输入作为字符串传递而不是函数的引用我不墨水,所以,只是日志'console.log(this.customSubmit);'你会得到真正的功能,而不是字符串 –
我已经更新另一种方式与@Output –