簡體   English   中英

Angular2:組件可以在另一個組件模板中使用嗎?

[英]Angular2: can component be used inside another component template?

我可以將組件放入另一個組件模板嗎? 例如聲明組件ImageBox具有選擇image和模板<img src="a.png"/>和在像另一個分量模板使用它<div>Something there. And some image too <image></image></div> <div>Something there. And some image too <image></image></div> -可以做到嗎?

這就是組件的用途

@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 {
}

您需要將組件和指令添加到要應用它們的組件的directives列表中。 角然后使每一個組件的一個選擇器相匹配標簽directives這樣的組件。

你可以這樣

文件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 { }

文件2

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

希望對您有所幫助

當在directives列表中編寫component時,聽起來很奇怪,但這是事實。

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 {
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM