Angular2初级篇之主从结构

    xiaoxiao2021-12-14  19

    前面一篇文章讲解了如何建立一个基础项目。若又不知道的请看前一篇文章,这里不做赘述了。

    先看一下目录结构:

    下面我们将写一个基础的列表显示。

    1、在app.component.ts中创建一个英雄数组:

    export class Hero {//英雄实体类   id: number;   name: string; } const HEROES: Hero[] = [//英雄数组 { id: 11, name: 'Mr. Nice' }, { id: 12, name: 'Narco' }, { id: 13, name: 'Bombasto' }, { id: 14, name: 'Celeritas' }, { id: 15, name: 'Magneta' }, { id: 16, name: 'RubberMan' }, { id: 17, name: 'Dynama' }, { id: 18, name: 'Dr IQ' }, { id: 19, name: 'Magma' }, { id: 20, name: 'Tornado' } ]; 以上代码放到import代码后面.

    2、修改app.component.ts来暴露英雄数组,以便进行绑定:

    export class AppComponent { title = "英雄之旅"; heroes = HEROES;//赋值给heros并把heros暴露出来以便绑定 }3、绑定heros到界面上:

     1)修改app.component.ts

    @Component({ moduleId: module.id, selector: 'my-app', templateUrl: 'app.component.html', styleUrls: ['../assets/css/app.component.css'] })2)、 创建app.component.html并修改

    <h2>英雄列表</h2> <ul class="heroes"> <li *ngFor="let hero of heroes"> <span class="badge">{{hero.id}}</span> {{hero.name}} </li> </ul>

    4、创建点击列表点击事件并绑定到界面上:

    1)、修改app.component.ts下AppComponent{...}

    建立自定义变量和点击事件:

    selectedHero: Hero;//自定义变量-英雄 onSelect(hero: Hero): void {//点击事件 this.selectedHero = hero; }2)、修改app.component.html

    <li *ngFor="let hero of heroes" (click)="onSelect(hero)"> <span class="badge">{{hero.id}}</span> {{hero.name}} </li>

    事件绑定详解

    COPY CODE (click)="onSelect(hero)"

    圆括号标识<li>元素上的click事件是绑定的目标。 等号右边的表达式调用AppComponent的onSelect()方法,并把模板输入变量hero作为参数传进去。 它是我们前面在ngFor中定义的那个hero变量。

    5、绑定选中的英雄到界面上:

    <div *ngIf="selectedHero"> <h2>{{selectedHero.name}}详情</h2> <div><label>id: </label>{{selectedHero.id}}</div> <div> <label>姓名: </label> <input [(ngModel)]="selectedHero.name" placeholder="name"/> </div> </div> 记住, ngIf 前导星号 ( * ) 是语法中的重要组成部分。

    最后别忘记添加上样式:

    <li *ngFor="let hero of heroes" [class.selected]="hero === selectedHero" (click)="onSelect(hero)"> <span class="badge">{{hero.id}}</span> {{hero.name}} </li>

    下面是css

    .selected { background-color: #CFD8DC !important; color: white; } .heroes { margin: 0 0 2em 0; list-style-type: none; padding: 0; width: 15em; } .heroes li { cursor: pointer; position: relative; left: 0; background-color: #EEE; margin: .5em; padding: .3em 0; height: 1.6em; border-radius: 4px; } .heroes li.selected:hover { background-color: #BBD8DC !important; color: white; } .heroes li:hover { color: #607D8B; background-color: #DDD; left: .1em; } .heroes .text { position: relative; top: -3px; } .heroes .badge { display: inline-block; font-size: small; color: white; padding: 0.8em 0.7em 0 0.7em; background-color: #607D8B; line-height: 1em; position: relative; left: -1px; top: -4px; height: 1.8em; margin-right: .8em; border-radius: 4px 0 0 4px; } 添加到相应的文件中就可以了。

    参考:https://angular.cn/docs/ts/latest/tutorial/toh-pt2.html

    转载请注明原文地址: https://ju.6miu.com/read-963118.html

    最新回复(0)