gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:14:27 25 4
gpt4 key购买 nike

在 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 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';
}
}

关于angularjs - 有没有办法将 Angular 2 属性指令传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42023286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com