2016-12-14 162 views
0

內部方法遵循下面的例子:角2:功能/上點擊的動態模板(動態組件)

How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

我開發我自己的模板生成器,它直接從變量獲取HTML內容。 這就是: http://plnkr.co/edit/2Sv1vp?p=preview

現在,我的問題是...如果模板內容必須與組件進行交互,例如用函數來執行上點擊......我該怎麼辦呢?

這裏我app.component.ts

import { Component }   from '@angular/core'; 

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div> 
     <h2>An app with DYNAMIC content</h2> 
     <hr /> 
     <dynamic-detail [tmpl]="tmpl1" [entity]="entity"></dynamic-detail> 
     <dynamic-detail [tmpl]="tmpl2" [entity]="entity"></dynamic-detail> 
    </div>`, 
    }) 
    export class AppComponent { 
    private tmpl: string; 
    private entity: any; 

    constructor() { 
     this.entity = { 
     code: "ABC123", 
     description: "A description of this Entity", 
     nome: "Bea" 
     }; 

     this.tmpl1 = '<h2>Sono {{entity.nome}}, il primo template</h2>'; 
     this.tmpl2 = '<a (click)="printSomething()">Sono il secondo template</a>'; 
     } 

    printSomething() { 
     console.log("Hello World"); 
    } 
} 

當我嘗試點擊 「索諾IL SECONDO模板」,應該執行printSomething()功能,而是我得到這個錯誤:

Error in ./CustomDynamicComponent class CustomDynamicComponent - inline template:0:0 caused by: self.context.printSomething is not a function 

回答

0

問題就像Angular說的那樣;您的動態創建的組件中不存在printSomething。如果我們聲明動態創建的組件中的功能,我們可以把它叫做:

app.component.ts

this.tmpl2 = '<a (click)="linkClicked()">Sono il secondo template</a>'; 

type.builder.ts

protected createNewComponent(tmpl: string) { 
    @Component({ 
     selector: 'dynamic-component', 
     template: tmpl, 
    }) 
    class CustomDynamicComponent implements IHaveDynamicData { 
     @Input() public entity: any; 

     linkClicked() { 
     console.log('yay!'); 
     } 

    }; 
    // a component for this particular template 
    return CustomDynamicComponent; 
    } 

如果要調用app.component.ts中的方法,則需要在CustomDynamicComponent的新@Input()屬性中傳遞對它的引用。

+0

哦,非常感謝你!這對我有用;) –