先自定义一个组件
import { Component } from '@angular/core';
@Component({
selector: 'exe-greet',
template: `
<div class="border">
<p>Greet Component</p>
<ng-content></ng-content>
</div>
`,
styles: [` .border { border: 2px solid #eee; } `]
})
export class GreetComponent { }
另一个父组件
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<h4>Welcome to Angular World</h4>
<exe-greet>
<p>Hello Semlinker</p>
</exe-greet>
`,
})
export class AppComponent { }
exe-greet指令使用时是<
exe-greet
></
exe-greet
>中间没有内容的,如果中间想要放不同内容,可使用ng-content占位符占位
由此可见ng-content是代指使用组件时内部的东西
除此之外ng-content 还有一个select属性
import { Component } from '@angular/core';
@Component({
selector: 'exe-greet',
template: `
<div style="border: 1px solid #666;margin: 4px;">
<div style="border: 1px solid red;margin: 5px;">
<ng-content select="header"></ng-content>
</div>
<div style="border: 1px solid green;margin: 5px;">
<ng-content select=".card_body"></ng-content>
</div>
<div style="border: 1px solid blue;margin: 5px;">
<ng-content select="footer"></ng-content>
</div>
</div>
`, styles: [` .border { border: 2px solid #eee; } `] }) export class GreetComponent{ }
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<h4>Welcome to Angular World</h4>
<exe-greet>
<header>Card Header</header>
<div class="card_body">Card Body</div>
<footer>Card Footer</footer>
</exe-greet>
`,
})
export class AppComponent { }