簡體   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