如何在Angular2中的其他组件内创建组件

时间:2016-09-25 10:50:51

标签: angular angular2-directives

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

enter image description here

1 个答案:

答案 0 :(得分:0)

以下是实现此目的的方法。

<强> 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>