【问题标题】:Pass local variable to directive as input将局部变量作为输入传递给指令
【发布时间】:2016-04-11 06:23:58
【问题描述】:

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

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

【问题讨论】:

    标签: angularjs-directive angular syntactic-sugar


    【解决方案1】:

    check plunker it works

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

    【讨论】:

    • 不只有一个参数,JSON如下:{"target":{"previousValue":{}}}
    • 请检查执行。我相信你的target 值会在args
    • backToTopTarget 有默认值吗?它必须工作有什么问题?
    【解决方案2】:

    我不确定$(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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-05
      • 1970-01-01
      • 2012-12-07
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 2011-09-10
      相关资源
      最近更新 更多