2017-07-16 18 views
2

請告訴怎麼做Angular2/4以下:angular2從只是一個字符串生成組件

組件SomeComponent@Input得到下面的HTML作爲一個字符串:

`<am-input 
    [placeholder]="'Placeholder'" 
    [disabled]="true"> 
    </am-input>` 

如何SomeComponent創建只有該字符串的內部組件?

謝謝

+0

的可能的複製[我怎麼手動消毒在angular2(https://stackoverflow.com/questions/38577347/how-do-i-manually-sanitize-in-angular2) – Aravind

+0

@Aravind您給出的示例 - 它們具有簡單html的字符串,而不是必須由之前的angular處理的html。或者這對DomSanitize無關緊要? –

回答

3

唯一的選擇是使用JIT編譯器,並在獲得它時進行編譯。閱讀Here is what you need to know about dynamic components in Angular,特別是Creating components on the fly部分。它詳細解釋了這個過程。以下是要點:

class SomeComponent { 
    @Input inputTpl; 
    constructor(private _compiler: Compiler, 
      private _injector: Injector, 
      private _m: NgModuleRef<any>) { 
    } 

    ngOnChanges() { 
    const tmpCmp = Component({template: inputTpl})(class {}); 
    const tmpModule = NgModule({declarations: [tmpCmp]})(class {}); 

    this._compiler.compileModuleAndAllComponentsAsync(tmpModule) 
     .then((factories) => { 
     const f = factories.componentFactories[0]; 
     const cmpRef = f.create(this._injector, [], null, this._m); 
     cmpRef.instance.name = 'dynamic'; 
     this.vc.insert(cmpRef.hostView); 
     }) 
    } 
+0

謝謝!這就是我在尋找的 –

+0

) –

+0

我收到以下錯誤:'錯誤錯誤:模板解析錯誤: 無法綁定到'佔位符',因爲它不是'am-input的已知屬性'。'但是我在'parent module'中導入了'am-input module'。雖然如果我傳遞給'Component()(class {})'而不是空類 - '準確的組件類'(我試圖動態生成)和'NgModule(..)(AmInputModule)'一樣' - 一切都好。但是'@ Input'可以傳遞很多組件。如果我需要傳入@Input不僅代碼,而且還傳入組件和模塊類,聽起來很難過。我怎樣才能避免這種情況? –