Angular的使用小结-新闻详情

Angular的使用小结


发布时间:2017-03-28责任编辑:朱明 浏览:1544


1、ngIfngFor的使用

 

    ngIfngForangular中的内部指令,分别相当于我们常用的ifforeach,值得注意的是ngIfngFor在使用的时候前面必须加上“*”,否则我们的程序会报错。

下面贴上一块代码,看看 ngIfngFor的具体使用方法:

<div class="form-group" *ngif="this.article.ContentType=='图文'">

    <label class="col-sm-2 control-label"><span style="color:#f00; vertical-align: sub;">*</span>内容</label>

    <div class="col-sm-10">

        <span *ngfor="let item of Content" [ngswitch]="item.type">

            <span *ngswitchcase="'image'">

                <tp-image [(adimgurl)]="item.ADImgUrl" [content]="Content" [item]="item">

                </tp-image>

            </span>

            <span *ngswitchcase="'text'">

                <tp-textarea [(jsoncontent)]="item.JsonContent" [content]="Content" [item]="item">

                </tp-textarea>

            </span>

        </span>

        <button (click)="addkongjian('image')">Add图片</button>

        <button (click)="addkongjian('text')">Add文本</button>

    </div>

</div>

从上面我们可以看出ngIf的后面跟的是一个表达式,返回一个boolen类型的值,这个值是true的话这个元素将会显示在DOM上,是false的话,将不会在DOM上显示。上面的Content是一个数组,通过ngFor来将Content中的每一个元素进行遍历。

 

2、数据的绑定

 

   Angular可实现数据的双向绑定,所谓的双向绑定就是界面与数据间的交互,数据的改变可以直接展示在界面上,界面上的操作也可以直接改变数据。

<td>{{p.Name}}</td>

<td>{{p.UserName}}</td>

<td>

    <span style="color:green" *ngif="p.State==1">开圈成功</span>

    <span style="color:red" *ngif="p.State==0">申请中</span>

    <span style="color:red" *ngif="p.State==2">禁用</span>

</td>

<td>{{p.ApplyReason}}</td>

<td>{{p.ZhiChiNum}}</td>

 

<div class="form-group">

    <label class="col-sm-2 control-label"><span style="color:#f00; vertical-align: sub;">*</span>标题</label>

    <div class="col-sm-10">

        <input class="form-control" type="text" placeholder="请输入标题" [(ngmodel)]="article.Title" name="Title" #title="ngModel">

    </div>

</div>

从上面的代码可以看出,{{}}实现数据的单向绑定,只是对数据的展示。而数据的双向绑定我们使用ngModel,article.Title的值会根据文本框中输入的值而改变。

 

3、分页以及数据的筛选

 

1Angular中数据的分页使用slice,具体实现如下:

 toggleSelectAll() {

      this.getList().slice((this.pageIndex - 1) * this.pageSize, this.pageIndex *         this.pageSize).forEach(p => {

             p.checked = this.isSelectAll;

       });

 }

其中this.getList()是数据集,pageIndex表示当前所在第几页,pageSize表示每页的条数,(this.pageIndex - 1) * this.pageSize, this.pageIndex * this.pageSize)即表示从第几条数据到第几条数据。

(2)Angular中数据的筛选使用filter,具体实现如下:

 

   search() {

        let searchlist = this.yijianList;

        if (this.Content != "" && this.Content != null) {

            searchlist = searchlist.filter(p => p.Content.includes(this.Content));

        }

        if (this.searchType != "" && this.searchType != null) {

            searchlist = searchlist.filter(p => p.Type==this.searchType);

        }

        return searchlist;

}

 

    总体来说,Angular2操作起来还是很方便的,对代码也具有严格的规范性,编译的时候也是遵循这种严格的模式,具有更高的可维护性。

 

诚信工作室  供稿