Directives

Using components in another one

In case you wish to use another components or directives in your component, all types of components/directives you wish to use has to be written in the directive array member of the ViewMetaData object. After doing that, all you need to do is simply put the directive.

For that, you need to do the following:

  1. Import the other component / directive type.
  2. Put the type you’ve imported in the directives array member of the ViewMetadata object.
  3. Use the directive / component as stated in its selector.

In the following example, let’s create a simple component and use it on another one.

This is the child component we’ll use:

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

@Component({selector: 'child-component',
 template: `<h2>This is an child component</h2>`
 })
 export class Childomponent{
 }

Now, let’s use it in another component:

/*Import the child component */
import {Childomponent} from 'path/to/childComponent';

@Component({selector: 'main-component',
template: `<h1>Main app Component</h1>
         <!-- using the child cmponent here -->
         <inner-component></inner-component>
         `
         /*Putting the child compont type in our directives*/
 directives: [Childomponent]
 })
 export class MainComponent{
 }

Note that forgetting to put the type in your directives array member won’t produce any error messages on your console, but won’t render your component.

Inter-component communication

You can pass data to and from a component you’re using. In order for our inner component to receive data to one of its class members, this class member is to be decorated by the Input decorator.

To demonstrate it, let’s alter our inner component a little bit.

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

@Component({selector: 'child-component',
 template: `<h2>{{componentName}}</h2>`
 })
 export class ChildComponent{
 @Input() componentName:string;
 }

We have added a property named componentName to the inner component preceded with the Input decorator, imported also from the @angular/core.

To show it, we’ve bounded it to the inner component template.

Now, all we need to do, is bind the componentName to a member in the main component.

/*Import the child component */
import {ChildComponent} from 'path/to/childComponent';

@Component({selector: 'main-component',
template: `<h1>Main app Component</h1>
         <!-- using the inner cmponent here -->
         <child-component [componentName]="childComponentName"></child-component>
         `
         /*Putting the child compont type in our directives*/
 directives: [Childomponent]
 })
 export class MainComponent{
   childComponentName: string;

   constructor(){
    this.childComponentName = "child component";
   }
 }

In Next Chapter you will learn about .. Using events