2017-05-30 55 views
1

我有一个简单的组件,它通过自定义指令中指定延迟后注入数​​Angular - 指令如何“看”模板和ViewContainer?

我已经知道*是角脱糖暗示的语法变得像

<ng-template ...> 
...actual markup 
</ng-template> 

我也知道我们可以通过注入组件/模板到viewContainer

this.viewContainerRef.createEmbeddedView/Component(this.templateRef); 

该指令代码:

@Directive({ 
    selector: '[appDelay]' 
}) 
export class DelayDirective { 
    constructor(
    private templateRef: TemplateRef<any>,private viewContainerRef: ViewContainerRef 
) { } 

    @Input() set appDelay(time: number): void { 
    setTimeout(()=>{ 
     this.viewContainerRef.createEmbeddedView(this.templateRef); 
    }, time); 
    } 
} 

的文档指出:

要访问一个元素的ViewContainerRef,您可以放置​​一个 指令与ViewContainerRef的元素注入,或者你通过ViewChild查询获得 它。

问:

一般模拟性:什么是templateRefviewContainerRef模板 “字符串值”?

恕我直言去加糖模板会是这样的:

<ng-tempalte ...> 
    <card *appDelay="500 * item"> 
     {{item}} 
    </card> 
</ng-template> 

所以ViewContainerRef<ng-tempalte ...>

一个参考,templateRef将在<card >...</card>

参考 - 那是对的吗 ?

(此外,是否有可能console.log()那些HTML模板,看看实际的标记?

https://plnkr.co/edit/80AGn8bR4CiyH0ceP8ws?p=preview

+1

你可能会发现[本条](https://hackernoon.com/exploring-angular-dom-abstractions-80b3ebcfc02)有用 –

回答

2

ViewContainerRef只是指向元素将主机插入的意见。这些意见将作为兄弟姐妹到该主机元素。

由于结构上的指令评论像<!---->将主机元素。

Desugar为

<div *appDelay="500"> 
    Hooray 
</div> 

<ng-template [appDelay]="500"> 
    <div> 
     Hooray 
    </div> 
</ng-template> 

它也可以像这样进行描述:

<ng-template view-container-ref></ng-template> 
<!-- ViewRef --> 
    <div> 
    Hooray 
    </div> 
<!-- /ViewRef --> 

由于ng-template不加盖到DOM它将呈现为<!---->

Angular将参照此评论标签创建ViewContainerRef

vcRef.element.nativeElement 

每个ViewContainer只能有一个锚点元素,每个锚点元素只能有一个ViewContainer。 ViewContainer是一个容器,可以帮助您处理意见(ViewRefEmbeddedViewRef

而且TemplateRef实例将被创建

class TemplateRef_ { 
    constructor(private _parentView: ViewData, private _def: NodeDef) { } 

    get elementRef(): ElementRef { 
    return new ElementRef(asElementData(this._parentView, this._def.index).renderElement); 
    } 

及其elementRef(锚或位置)将指向相同的注释元素。

TemplateRef的主要特征是具有template财产

this.templateRef._def.element.template 

此属性不包含HTML字符串,但描述view

this.templateRef._def.element.template.factory + '' 

将打印

"function View_AppComponent_1(_l) { 
    return jit_viewDef1(0,[(_l()(),jit_elementDef2(0,null,null,1,'div',[],null,null, 
     null,null,null)),(_l()(),jit_textDef3(null,['\n Hooray\n']))],null,null); 
}" 

所以这是我们的模板。正如你可以看到它描述了与文本div根元素和子文本节点视图\n Hooray\n

角用途,例如ViewDefinitions分别位于ngfactories构建DOM树enter image description here

参见

不要忘记观看https://www.youtube.com/watch?v=EMjTp12VbQ8

+0

这应该是在文档.no开玩笑 –

+0

ViewContainerRef和TemplateRef引用相同的注释标记https://monosnap.com/file/gTzAjV2beEJm7Yp4Ujetleja7gHvpw但是TemplateRef在其实例信息中存储了关于嵌入模板的信息 – yurzui

+0

谢谢,像往常一样 –