【问题标题】:How to create component inside other component in Angular2如何在Angular2中的其他组件内创建组件
【发布时间】:2016-09-25 10:50:51
【问题描述】:

我需要使用模板中的指令将一个复杂的组件拆分为两个或多个更简单的组件。

【问题讨论】:

    标签: angular angular2-directives


    【解决方案1】:

    这是如何实现这一点的方法。

    MainComponent.ts

    import { Component } from '@angular/core';
    import { MyService1 } from '../../providers/myService1/myService1';
    import { MyCmp1 } from '../../components/myCmp1/myCmp1';
    
    @Component({
       templateUrl: 'build/pages/mainComponent/mainComponent.html',
       providers: [
          MyService1
       ],
       directives: [
          MyCmp1
       ],
       //pipes: [ ... ] // Pipes which you are using
    })
    export class MainComponent {
       main: any;
    
       constructor() {
          this.load();
       }
    
       load(): void {
           MyService1.loadData()
              .then((response) => {
                   main.data1 = response;
              });
       }
    
       onShowMe(data): void {
           alert(data);
       }
    }
    

    MainComponent.html

    <div class="main-component">
       <h1>Main Component</h1>
       <my-cmp-1 [data1]="main?.data1" (onShowMe)="onShowMe($event)"></my-cmp-1>
    </div>
    

    MyCmp1.ts

    import { Component, EventEmitter } from '@angular/core';
    import { Input, Output } from '@angular/core';
    
    @Component({
       selector: 'my-cmp-1',
       templateUrl: 'build/components/myCmp1/myCmp1.html'
    })
    
    export class MyCmp1 {
       @Input() data1: any;
       @Output() onShowMe = new EventEmitter();
    
       showMe(event: Event, data: any): void {
          event.preventDefault(); // If you are using <a> or etc.
          this.onShowMe.emit(data);
       }
    }
    

    MyCmp1.html

    <h3>My Component 1</h3>
    <a href="" (click)="showMe($event, 'message from MyCmp1')">Show Me</a>
    

    【讨论】:

      猜你喜欢
      • 2016-06-09
      • 1970-01-01
      • 2013-12-08
      • 2017-01-26
      • 2014-01-10
      • 2016-12-07
      • 2018-02-02
      • 2021-09-24
      • 2023-04-09
      相关资源
      最近更新 更多