在angularJS中,一个指令允许你做:
angular.module('Directives').directive('myButton', [() => {
return {
restrict: 'E',
template: '<button ng-click="callback()"></button>',
bindings: { callback: '&' },
};
}]);
,像这样使用
<my-button callback="someCallback"></my-button">
# controller:
scope.someCallback = () => { alert('hi'); };
…
当我用一个现代的angular组件替换该指令时:
@Injectable({ providedIn: 'root' })
@Component({
selector: 'my-button',
template: '<button (click)="click()"></button>'
})
export class MyButtonComponent {
@Input() callback: () => void;
click () {
this.callback();
}
}
当我在现代Angular中使用它时效果很好,比如:
@Injectable({ providedIn: 'root' })
@Component({
selector: 'wrapper',
template: '<my-button [callback]="someFunc"></my-button>'
})
export class WrapperComponent {
someFunc: () => void;
constructor() {
this.someFunc = () => { alert('hi'); }
}
}
…但是,如果我将该组件降级为混合应用:
angular.module('Directives').directive('myButton', downgradeComponent({ component: MyButtonComponent }))
然后尝试在angularJS中使用这个,回调输入得到一个字符串值someCallback
,而不是将实际的函数传递给组件…
我能弄清楚如何使其工作的唯一方法是使用输出并发出…
export class MyButtonComponent {
@Output() callback = new EventEmitter();
click () {
this.callback.emit();
}
}
然后像这样使用:
<my-button (callback)="someFunc()"></my-button>
是否有一种方法可以告诉降级的组件,输入有一个'&'
绑定,这样我就不必使用输出,因此必须改变所有使用该指令的angularJS模板的标记?
你如何在模板中使用这个指令?
你应该使用这种新的Angular方式:
<my-button [callback]="someFunc"></my-button>
代替:
<my-button callback="someFunc"></my-button>
对于降级的组件,括号是必须的,否则就像把字符串传递给Angular 2+组件一样。