[英]Angular JS - Is there a way to pass the directive's attribute to the template
[英]Is there a way to pass an Angular 2 attribute directive a function
在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]()
嘗試這個:
@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);
}
}
應用程序/ 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在線演示@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';
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.