我想将ElementRef
backToTopTarget传递给指令.back-to-top
。然而,我无法用ngOnChanges
获得它
<section #backToTopTarget>
<section class="back-to-top" [target]="backToTopTarget">
Back to top <i class="fa fa-angle-up"></i>
</section>
</section>
/// <reference path="../../../typings/angular2.d.ts" />
import {Directive, Input, OnChanges, ElementRef} from 'angular2/core';
import {BaseComponent} from "../../BaseComponent/BaseComponent";
@Directive({
selector: '.back-to-top',
})
export class BackToTop implements OnChanges {
private $el;
@Input('target') private target;
private $target;
constructor(private el: ElementRef) {
this.$el = $(this.el.nativeElement);
}
ngOnChanges({target}) {
// target.currentValue === undefined
}
}
所以我不能或者我做错了什么?
检查plunker是否工作
ngOnChanges(...args:any[])
{
console.log(args[0].target); // according to my plunker code
}
我不确定$(this.el.nativeElement)
应该做什么。
这对我来说很好:
@Directive({
selector: '.back-to-top',
})
export class BackToTop implements OnChanges {
private $el;
@Input() private target;
private $target;
constructor(private el: ElementRef) {
this.$el = this.el.nativeElement;
}
ngOnChanges(changes) {
console.debug(this.target);
// outputs `<section></section>`
}
}
@Component({
selector: 'my-app',
directives: [BackToTop],
template:`
<section #backToTopTarget>
<section class="back-to-top" [target]="backToTopTarget">
Back to top <i class="fa fa-angle-up"></i>
</section>
</section>
`,
})
export class App {
}
Plunker示例