Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Angular模板标签<ng-container>、<ng-template> #21

Open
alanhg opened this issue Dec 7, 2017 · 2 comments
Open

Angular模板标签<ng-container>、<ng-template> #21

alanhg opened this issue Dec 7, 2017 · 2 comments

Comments

@alanhg
Copy link
Owner

alanhg commented Dec 7, 2017

No description provided.

@alanhg
Copy link
Owner Author

alanhg commented Dec 7, 2017

ng-template我们经常搭配ngIf指令等使用,如下:

<div *ngIf="isList;else elseBlock">
    <ul>
        <li *ngFor="let item of items">
            <a routerLink='../detail/{{item.id}}' [queryParams]="{title:item.title}">
                {{item.title}}
            </a>
        </li>
    </ul>
</div>
<ng-template #elseBlock>
    <div>
        分组浏览
    </div>
</ng-template>

但是,这样子,比如为true时候,我们生成的code中是会多了个if所谓的标签div,有时候我们是不需要这个的,如何不额外增加div标签呢,答案是使用ng-container标签。

<ng-container *ngIf="isList;else elseBlock">
    <ul>
        <li *ngFor="let item of items">
            <a routerLink='../detail/{{item.id}}' [queryParams]="{title:item.title}">
                {{item.title}}
            </a>
        </li>
    </ul>
</ng-container>
<ng-template #elseBlock>
    <div>
        分组浏览
    </div>
    <div *ngFor="let i of [1,2,3]">
        <h3> {{i}}</h3>
    </div>
</ng-template>

@alanhg
Copy link
Owner Author

alanhg commented Dec 7, 2017

注意

如上代码如果这样子去写,if块中内容就不会正常显示

<ng-template *ngIf="isList;else elseBlock">
    <ul>
        <li *ngFor="let item of items">
            <a routerLink='../detail/{{item.id}}' [queryParams]="{title:item.title}">
                {{item.title}}
            </a>
        </li>
    </ul>
</ng-template>
<ng-template #elseBlock>
    <div>
        分组浏览
    </div>
    <div *ngFor="let i of [1,2,3]">
        <h3> {{i}}</h3>
    </div>
</ng-template>

原因,ng-template目的是声明一个模板,本身并不是个容器

相关issue

@alanhg alanhg changed the title angular模板标签<ng-container>、<ng-template> Angular模板标签<ng-container>、<ng-template> Dec 7, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant