【Angular Tips】开发Angular2+应用有用的tips... 【持续更新】

1. 使用ng-content来作内容填充

有的时候,咱们可能但愿在一个组件里面动态的嵌入其余组件,咱们除了使用*ngIf来动态地显示或隐藏其余组件,还可使用ng-content来作。code

好比咱们定义一个组件:
在template里面加入<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>
    `
})

在其余组件中咱们来使用刚才定义的组件:it

<quote>
   <h4>Way to go.</h4>
   <h6>Keep up the good work.</h6>
</quote>

这个时候,h4和h6就会被添加到组件quote中。angular

//Output
I will never let you down.
And you will never walk alone.
Way to go.
Keep up the good work.

那假如咱们但愿根据不一样的状况也选择添加不一样的组件呢? 固然咱们可使用*ngSwitchCase来作,但实际上ng-content已经给咱们添加了一个select属性,来能够选择显示指定的组件:容器

修改一下咱们的quote组件, 我只但愿显示标签名是h4的组件,因此使用select="h4"变量

@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就会被添加到组件quote中。select

//Output
I will never let you down.
And you will never walk alone.
Way to go.

除了能够直接指定元素的标签外,还能够经过[attr]的方式来绑定元素的某一个属性,而后指定显示有这个属性的元素。样式

咱们继续来修改组件quote, 咱们使用select="[show]"来指定显示全部有show属性的元素:margin

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

这个时候,指定标签显示的h4和指定属性show显示的h5h6就会被添加到组件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应用时,咱们常常会用到结构化指令ngIf来动态显示某一段代码

好比下面的例子

<div *ngIf="show">
   <div>Div One</div>
   <div>Div Two</div>
</div>

咱们使用了div来包裹两个子div, 而后经过变量show来动态显示或者隐藏。
但这却不是最好的解决方案, 缘由有两个:
1). 咱们在DOM中添加了一个没必要要的节点div
2). 这个添加的div节点有可能会搞乱咱们的样式。

那有没有更好一点的解决方式呢?
有的, angular提供了ng-container来帮助咱们更好的来包裹代码,并且不会在DOM创造没必要要的节点。
因此咱们能够直接这样使用:

<ng-container *ngIf="show">
   <div>Div One</div>
   <div>Div Two</div>
</ng-container>

ng-container是一个逻辑容器,可用于来分组节点,并且不会在DOM中被渲染成节点, 而是会被渲染成一个comment.
ng-container 不只能够用来搭配使用ngIf,还能够搭配使用ngSwitch中的ngSwitchCase,这样咱们就不必建立出多余的tag了。

因此说,使用ng-container最大的好处就是让咱们的template更干净了,没有冗余节点。

相关文章
相关标签/搜索