Angular2(单击)动态加载组件视图

时间:2017-03-18 22:18:15

标签: angular dynamic

我在点击时创建了动态加载组件视图,但我每次点击都是单独的。我想有函数,我通过函数传递一个字符串,而不是在我的函数中输入该字符串来加载视图。

这是一个工作的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)中传递并加载视图的变量。 这是一个尝试的掠夺者: 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'

    },


];

1 个答案:

答案 0 :(得分:6)

使用以下代码

@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
    }];

<强> LIVE DEMO