2016-05-23 73 views
6

大家都知道Angular2没有ng-init或其他东西。所以,如果我们尝试做这样做:Angular2没有ng-init

<div #rr="2+2"> 
{{rr}} 
</div> 

我们会得到运行时错误:

Error: There is no directive with "exportAs" set to "2+2"

我是看对youtube的Angular2开发的视频之一,看到一模一样的建设意味着工作。 以下是屏幕截图: enter image description here

这是对用户模板变量的赋值可能吗?

+2

很难说。你能否提供一个演示这个工作的Plunker?任何人都可以在任何地方投射代码。这并不意味着它是有意义的。 –

回答

2

局部变量旨在引用上述两个电流DOM元素:

<div #elt></div> 

或特定元件施加的元件上:

<div #elt="someDirective" dir></div> 

someDirective对应于该指令的exportAs值:

@Directive({ 
    selector: '[dir]', 
    exportAs: 'someDirective' 
}) 

您不能使用m来定义别的东西。这就是消息实际讲述的内容......

+0

这应该是被接受的答案。 –

5

#rr与ng-init不等价。 ng-init不见了,不会回来 - 你需要显式初始化组件类中的字段(等同于初始化范围)。

您可以使用@Directive注释的exportAs属性。它导出要在父视图中使用的指令。在父视图中,可以将其绑定到视图变量,并使用@ViewChild()从父类访问它。

您可以阅读更多关于exportAs here

请检查样本演示实施出口至here

+0

我同意,但我在视频中看到的是相反的。在我的问题中看截图。 – Dizzy

+1

链接已损坏。去404消息。 –

1

为了能够模板内声明的变量,你可以利用,如自定义结构的指令:

@Directive({ 
    selector: '[ngInit]', 
}) 
export class NgInitDirective { 
    @Input() 
    set ngInit(context: any) { 
    this.context.$implicit = this.context.ngInit = context; 
    this.vcRef.clear(); 
    this.vcRef.createEmbeddedView(this.templateRef, this.context); 
    } 

    context: { $implicit?: any, ngInit?: any } = {}; 

    constructor(private vcRef: ViewContainerRef, private templateRef: TemplateRef<any>) {} 
} 

之后如下您可以编写代码:

<div *ngInit="2+2 as rr"> 
    {{rr}} 
</div> 

<div *ngInit="2+2; let rr"> 
    <span>{{rr}}</span> 
</div> 

Plunker Example

+0

感谢您的指示。但是,如果您从我的第一篇文章中看到图片或视频,那么对于阅读您的模板的人来说,这种表示法会更加清晰。问题是怎么可能的?仍然没有答案。 – Dizzy