estus estus - 1 year ago 228
Javascript Question

Angular 2 expression parser and ng-init directive

Basically I'm looking for a way to implement a counterpart to Angular 1.x


I'm aware of
hook and the fact that it is the recommended place for initialization code. I consider
directive a quick, declarative way to prototype or fix a component that shouldn't be generally used in well-written production code (although a developer has the right to choose what's best for him/her).

Doing something like that in
dummy directive

<p [init]="foo = 1; bar()"><p>

evaluates the expression more than one time and causes

Template parse errors:

Parser Error: Bindings cannot contain assignments


In Angular 1.x it could be done just with


How can Angular 2 parser be used and possibly extended to evaluate
foo = 1; bar()
template expression on component initialization?

Answer Source

It is

@Directive({ selector: '[initialize]' })
class InitializeDirective {
  @Output() initialize = new BehaviorSubject();


<div initialize (initialize)="initViaMethodCall(); foo = 'init via assignment'">
  <template initialize (initialize)="bar = 'init with no extra markup'"></template>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download