Angular2指令与范围

时间:2016-05-17 15:43:40

标签: javascript angular angular2-directives

Angular2中的指令没有"范围",而组件则没有。但就我而言,我需要Directive来创建一个范围。查看我的App组件 - 它有一个HTML模板,并且foo指令可能出现在任何元素上的ANYWHERE。这应该从服务中获取一些日期并将其分配给元素。

在Angular1中,它很容易......指令可以有自己的范围。但是在Angular 2中,我找不到任何(甚至是肮脏的)方法来实现它。

这看起来像一个简单的任务,不是吗?

@Directive({
  selector: '[foo]'
})
class FooDirective {
  @Input()
  public id:string;

  public bar;

  constructor() {
     this.bar = 'This is the "bar" I actually need. It is taken from DB let's say..' + this.id;
  }
}




@Component({
  selector: 'app',
  template: `
     <div foo id="2">
       This is random content 1: {{bar}}
     </div>

     <div foo id="2">
       This is random content 2: {{bar}}
     </div>
  `,
  directives: [FooDirective]
})
class App {
  bar:string = 'This should be ignored, I need "bar" to be set from directive!';
}

bootstrap(App);

2 个答案:

答案 0 :(得分:5)

你可以尝试使用一个引用应用指令的局部变量:

@Component({
  selector: 'app'
  template: `
    <div foo id="2" #dir1="foo">
      This is random content 1: {{dir1.bar}}
    </div>

    <div foo id="2" #dir2="foo">
      This is random content 2: {{dir2.bar}}
    </div>
  `,
  directives: [FooDirective]
})
class App {
  bar:string = 'This should be ignored, I need "bar" to be set from directive!';
}

在您的情况下,bar使用当前组件的属性App进行评估。

修改(关注@ yurzui&#39;评论)

您需要在指令中添加exportAs属性:

@Directive({
  selector: '[foo]',
  exportAs: 'foo'
})
class FooDirective {
  (...)
}

答案 1 :(得分:0)

当你说组件确实有范围时,意味着什么?

我的理解是组件之间没有共享对象(或原型继承)。但我认为这就是你要找的 - 你希望FooDirective和App共享同一个(范围)对象,对吗?如果是这样,我不认为Angular 2中有任何等价物。

我怀疑你是否会喜欢这个,但我能想出的最好的(与@ Thierry的方法不同)是使用div作为&#34;分享对象&#34; (而不是指令)。该指令使用HostBinding将值保存到div上的数据属性,然后组件使用局部变量检索模板中的该值,以获取对div /共享对象的引用: / p>

import {Component, Directive, Input, HostBinding} from '@angular/core';

@Directive({selector: '[foo]'})
class FooDirective {
  @Input() id:string;
  @HostBinding('attr.data-bar') bar;
  ngOnInit() {
     this.bar = 'This is "bar" I actually need. It is taken from DB lets say...' + this.id;
  }
}

@Component({
  selector: 'my-app',
  template: `{{title}}<p>
    <div #div1 foo id="2">
      This is random content 1: {{div1.getAttribute('data-bar')}}
    </div>`,
  directives: [FooDirective]
})
export class AppComponent {
  title = `Angular - RC.1`;
}

Plunker

我更喜欢@ Thierry的方法比我上面所说的更好,但我想我会发布我正在玩弄的东西。

相关问题