简体   繁体   English

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

[英]Pass local variable to directive as input

I want to pass ElementRef backToTopTarget to directive .back-to-top . 我想将ElementRef backToTopTarget传递给指令.back-to-top However I cannot get it with ngOnChanges 但是我无法通过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
    }
}

So I cannot or anything I am doing it wrong? 所以我不能或做错任何事吗?

check plunker it works 检查插塞工作

ngOnChanges(...args:any[])
{
    console.log(args[0].target); // according to my plunker code
}

I'm not sure what $(this.el.nativeElement) is supposed to do. 我不确定$(this.el.nativeElement)应该做什么。

This works fine for me: 这对我来说很好:

@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 柱塞示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM