[英]Angular2 (click) load dynamically the component view
我創建了單擊以動態加載組件視圖,但我每次單擊都是單獨的。 我想有函數,我通過函數傳遞一個字符串,而不是在我的函數中輸入該字符串來加載視圖。
這是一個工作的plunker http://plnkr.co/edit/ZXsIWykqKZi5r75VMtw2?p=preview
零件
@Component({
selector: 'my-app',
template: `
<div>
<h2>Lets dynamically create some components!</h2>
<button (click)="createHelloWorldComponent()">Create Hello World</button>
<button (click)="createWorldHelloComponent()">Create World Hello</button>
<dynamic-component [componentData]="componentData"></dynamic-component>
</div>
`,
})
export class App {
componentData = null;
createHelloWorldComponent(){
this.componentData = {
component: HelloWorldComponent,
inputs: {
showNum: 9
}
};
}
createWorldHelloComponent(){
this.componentData = {
component: WorldHelloComponent,
inputs: {
showNum: 2
}
};
}
}
想要的是一個函數,並從數組中定義一個在(click)中傳遞並加載視圖的變量。 這是一個嘗試的plunker: http ://plnkr.co/edit/HRKGhCCEfkOhNjXbr6C5?p = preview
@Component({
selector: 'my-app',
template: `
<div>
<h2>Lets dynamically create some components!</h2>
<li *ngFor="let item of myMenu">
<button (click)="loadView({{ item.viewname }})">{{ item.id }}</button>
</li>
<dynamic-component [componentData]="componentData"></dynamic-component>
</div>
`,
})
export class App {
componentData = null;
myMenu = {};
constructor() {
this.myMenu = myMenu;
}
loadView(viewName){
this.componentData = {
component: viewName,
inputs: {
showNum: 9
}
};
}
}
const myMenu = [
{
id: 1,
viewname: 'HelloWorldComponent'
},
{
id: 2,
viewname: 'WorldHelloComponent'
},
];
使用以下代碼,
@Component({
selector: 'my-app',
template: `
<div>
<h2>Lets dynamically create some components!</h2>
<button (click)="createComponent($event)">Create Hello World</button>
<button (click)="createComponent($event)">Create World Hello</button>
<dynamic-component [componentData]="componentData"></dynamic-component>
</div>
`,
})
組件方法將具有以下代碼
createComponent(val){
if(val.srcElement.innerHTML==='Create Hello World')
{
this.createHelloWorldComponent()
}
if(val.srcElement.innerHTML==='Create World Hello'){
this.createWorldHelloComponent()
}
}
LIVE DEMO更新了您的plunker。
更新1:當你還沒准備好在if條件中處理它們時,你應該有一個映射屬性來根據被點擊的項返回componentData。
var myComponents =[{
id : 1,
component: HelloWorldComponent,
inputs: { showNum: 9 }
},{
id : 2,
component: WorldHelloComponent,
inputs: { showNum: 0 }
}];
var myMenu = [{
id: 1,
viewname: 'HelloWorldComponent',
componentID : 1
},
{
id: 2,
viewname: 'WorldHelloComponent',
componentID : 2
}];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.