簡體   English   中英

動態實例化ng模板並以角度5創建HTML

[英]dynamically instantiate an ng-template and create HTML in angular 5

我試圖建立一個typeahead.js在角5.使用我有一個組件工作plunker ,只要我能得到它的工作。

聲明組件type-head ,將向組件提供ng-template

<type-head>
    <ng-template #hint let-hint="hint">name: {{hint.name}}</ng-template>
</type-head>

每個提示應顯示name: sam|frodo|pippin等。

type-head組件聲明如下:

@Component({
  selector: 'type-head',
  template: `
    <input #input class="form-control" />
    <ng-content #content></ng-content>
  `
})

typeahead.js組件需要顯示的提示,它執行的回調,該suggest方法應返回HTML內容。

目前,我的實現如下:

/**
 * TODO: REPLACE THIS FUNCTION WITH A DYNAMIC TEMPLATE
 */
suggest(value:any) {
   return $("<div>name: " + value.name + "</div>");
}

我想將此實現替換為使用ng-template 我可以使用*ngTemplateOutlet渲染模板,但是我不知道如何動態地執行它,因此我可以返回HTML。

我的問題是:

如何加載了#hint ng-template ,綁定value到它,並且呈現的HTML返回typeahead.js在我的suggest功能。

您可以使用TemplateRef::createEmbeddedView方法創建嵌入式視圖,然后獲取DOM節點作為模板傳遞給typeahead:

parent.html

<type-head>
    <ng-template #hint let-hint="hint">
       <div>name: {{hint.name}}</div>
    </ng-template>
</type-head> 

component.ts

@ContentChild(TemplateRef) templateRef: TemplateRef<any>;

suggest(value:any) {
  const embeddedView = this.templateRef.createEmbeddedView({ hint: value });
  embeddedView.detectChanges();
  this.embeddedViews.push(embeddedView);
  return embeddedView.rootNodes[1];
}

柱塞示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM