簡體   English   中英

將局部變量傳遞給指令作為輸入

[英]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
    }
}

所以我不能或做錯任何事嗎?

檢查插塞工作

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 {
}

柱塞示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM