将局部变量作为输入传递给指令

Pass local variable to directive as input

我想将 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
    }
}

所以我不能或我做错了什么?

check plunker it works

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 example