angular4.x绑定数据、循环*ngFor、条件判断 *ng

2018-07-12  本文已影响0人  考拉狸猫

一、angular4.x运行项目

1、如果没有安装依赖包node_modules,则需要cnpm install 安装依赖

2、运行项目,在项目下ng serve --open运行项目

二、创建组件

ng g component components/header

三、angualr4.x 绑定数据

1. 数据文本绑定{{}}

.ts

public title='数据文本绑定';

.html

<div>{{title}}</div>

2.绑定 html

.ts

public htmlText:any;

this.htmlText="<h2>绑定 html</h2>"

.html

<div [innerHTML]="htmlText">

四、 数据循环 *ngFor="let item of list"

1、不带下标循环

.ts

public list=[];//声明一个空数组

for(let i=0;i<10;i++){//模拟假数据

      this.list.push('第'+i+'条数据')

    } 

.html

<ul>

    <li *ngFor="let item of list">{{item}}</li>

</ul>

1、带下标循环*ngFor="let item of list;let i=index"

.html

<ul>

    <li *ngFor="let item of list;let i=index">{{item}}---{{i}}</li>

</ul>

五、条件判断 *ngIf

.ts

public list=[];//声明一个空数组

for(let i=0;i<10;i++){//模拟假数据

      this.list.push('第'+i+'条数据')

    } 

.html

    <ul>

        <p *ngIf="list.length<5">//如果list的长度小于5,则不显示数据

             <li *ngFor="let item of list;let i=index">{{item}}---{{i}}</li>

        </p>

    </ul>

    六、绑定执行事件

    .ts

    public msg="绑定事件";

    this.run();//调用

    run(){

        console.log(this.msg)

      }

    .html

    <button (click)="run()">点击</button>

    七、绑定属性

    1、添加id和class

    .ts

    public id='addId';

    public class="addClass"

    .html

    <div [id]="id" [class]="class">添加id和class</div>

    2、添加title

    .ts

    public titleMsg="";

    this.titleMsg="设置title";

    .html

    <div [title]="titleMsg">鼠标移上去</div>

    八、表单输入、表单处理(keyup)="keyUp($event)"

    .ts

    keyUp(e){//键被松开

        console.log(e);     

      }

    .html

    <input type="text" (keyup)="keyUp($event)">

    九、表单双向数据绑定

    注入FormsModule 

    app.module.ts

    import { FormsModule } from '@angular/forms';

    imports: [

        FormsModule,

      ],

    .ts

    public userName="";

    keyUp(e){//键被松开

        console.log(this.userName);     

      }

    .html

    <input type="text" [(ngModel)]="userName" (keyup)="keyUp($event)"/>

    上一篇 下一篇

    猜你喜欢

    热点阅读