繁体   English   中英

Angular2指令与范围

[英]Angular2 Directive with scope

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);

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

@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!';
}

在您的情况下,使用当前组件( App one)的属性评估bar

编辑 (关注@ yurzui的评论)

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

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

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

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


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

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的方法,而不是我上面展示的方法,但我认为无论如何我都会发布我正在玩的东西。

暂无
暂无

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

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