Arman Hayots
Arman Hayots

Reputation: 2508

Angular2: can component be used inside another component template?

Can I put component into another component template? E.g. declare component ImageBox with selector image and template <img src="a.png"/> and use it in another component template like <div>Something there. And some image too <image></image></div> — is this can be done?

Upvotes: 0

Views: 4052

Answers (3)

Anshul
Anshul

Reputation: 9480

It sound weird when we write component , inside our directives list, but this is the way it is.

import {Component} from 'angular2/core';


@Component({
    selector:   'my-app',
    template:   '<div>hello <innerComponent></innerComponent></div>',
    directives: [InnerComponent]  
   // mistake point (component in directive list)
})

export class AppComponent { }


@Component({
  selector: 'innerComponent',
  template: '<img src="a.png"/>'
})
export class InnerComponent {
}

Upvotes: 0

Angel Angel
Angel Angel

Reputation: 21678

You can do it this way

file 1

import {Component} from 'angular2/core';
import {ImageBox}  from './file 2';


@Component({
    selector:   'my-app',
    template:   '<div>Something there. And some image too <selectorNameImageBox></selectorNameImageBox> </div>',
    directives: [ImageBox]
})

export class AppComponent { }

file 2

@Component({
  selector: 'selectorNameImageBox',
  template: '<img src="a.png"/>'
})
export class ImageBox {
}

I hope it will help

Upvotes: 0

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657308

This is what components are for

@Component({
  selector: 'image',
  template: '<img src="a.png"/>'
})
export class ImageBox {
}

@Component({
  selector: 'other',
  directives: [ImageBox],
  template: '<div>Something there. And some image too <image></image></div>'
})
export class OtherComponent {
}

You need to add components and directives to the directives list of the component where you want them to be applied. Angular then makes each tag that matches a selector of a component in directives such a component.

Upvotes: 1

Related Questions