Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Directive with scope

Directives in Angular2 do not have "scopes", while Components do. But in my case I need Directive to create a scope. Look at my App component - it has an HTML template, and ANYWHERE on any element the foo directive could appear. This should grab some date from service and assign it to the Element.

In Angular1 it was very easy... Directives could have its own scope. But in Angular 2 I cannot find any (even dirty) way to achieve that.

It looks like a simple task, doesn't it?

@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);
like image 841
Arūnas Smaliukas Avatar asked Dec 05 '25 13:12

Arūnas Smaliukas


1 Answers

You could try something like that leveraging a local variable that would reference the applied directive:

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

In your case bar is evaluated using properties of the current component, the App one.

Edit (following the @yurzui's comment)

You need to add an exportAs property in your directive:

@Directive({
  selector: '[foo]',
  exportAs: 'foo'
})
class FooDirective {
  (...)
}
like image 145
Thierry Templier Avatar answered Dec 07 '25 02:12

Thierry Templier