Angular 2 表达式解析器和 ng-init 指令 [英] Angular 2 expression parser and ng-init directive

查看:21
本文介绍了Angular 2 表达式解析器和 ng-init 指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我正在寻找一种方法来实现 Angular 1.x ngInit 指令的对应项.

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

我知道 ngOnInit 钩子以及它是初始化代码的推荐位置的事实.我认为 ngInit 指令是一种快速、声明性的方法来原型化或修复通常不应该在编写良好的生产代码中使用的组件(尽管开发人员有权选择最适合他/她的组件)).

I'm aware of ngOnInit hook and the fact that it is the recommended place for initialization code. I consider ngInit 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).

init 伪指令中做类似的事情

Doing something like that in init dummy directive

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

多次计算表达式并导致

模板解析错误:

解析器错误:绑定不能包含赋值

Parser Error: Bindings cannot contain assignments

错误.

在 Angular 1.x 中,只需使用

In Angular 1.x it could be done just with

$parse($attrs.init)($scope)

如何使用 Angular 2 解析器并可能扩展以评估 foo = 1;bar() 组件初始化的模板表达式?

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

推荐答案

这可以通过指令来实现:

This can be achieved with a directive:

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

预期用途是:

<div (initialize)="initViaMethodCall(); foo = 'init via assignment'"></div>
<ng-template (initialize)="bar = 'init with no extra markup'"></template>
{{ foo }}
{{ bar }}

这篇关于Angular 2 表达式解析器和 ng-init 指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆