【Angular Tips】开发Angular2+应用有用的tips... 【持续更新】
1. 使用ng-content来做内容填充有的时候,我们可能希望在一个组件里面 比如我们定义一个组件: @Component({ selector: 'quote',template: ` <div style="margin: 20px;"> <h1>I will never let you down.</h1> <h2>And you will never walk alone.</h2> <ng-content></ng-content> </div> ` }) 在其他组件中我们来使用刚才定义的组件: <quote> <h4>Way to go.</h4> <h6>Keep up the good work.</h6> </quote> 这个时候,h4和h6就会被添加到组件 //Output I will never let you down. And you will never walk alone. Way to go. Keep up the good work. 那假如我们希望根据不同的情况也选择添加不同的组件呢? 当然我们可以使用 修改一下我们的 @Component({ selector: 'quote',template: ` <div style="margin: 20px;"> <h1>I will never let you down.</h1> <h2>And you will never walk alone.</h2> <ng-content select="h4"></ng-content> </div> ` }) 在其他组件中我们还是来使用刚才定义的组件quote: <quote> <h4>Way to go.</h4> <h6>Keep up the good work.</h6> </quote> 这个时候,只有h4就会被添加到组件 //Output I will never let you down. And you will never walk alone. Way to go. 除了可以直接指定元素的标签外,还可以通过 我们继续来修改组件 @Component({ selector: 'quote',template: ` <div style="margin: 20px;"> <h1>I will never let you down.</h1> <h2>And you will never walk alone.</h2> <ng-content select="h4"></ng-content> <ng-content select="[show]"></ng-content> </div> ` }) 在其他组件中我们还是来使用刚才定义的组件quote: <quote> <h4>Way to go.</h4> <h6 show>Keep up the good work.</h6> <h5 show>And Never give up.</h5> </quote> 这个时候,指定标签显示的 //Output I will never let you down. And you will never walk alone. Way to go. Keep up the good work. And Never give up. 2. 使用ng-container来搭配结构化指令包裹代码在开发angular应用时,我们经常会用到结构化指令 比如下面的例子 <div *ngIf="show"> <div>Div One</div> <div>Div Two</div> </div> 我们使用了 那有没有更好一点的解决方式呢? <ng-container *ngIf="show"> <div>Div One</div> <div>Div Two</div> </ng-container>
所以说,使用 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |