Angular 使用总结(三)组件之结构指令

Angular 应用几乎不可能不用结构指令

 

总结常见的结构指令:

1. *ngFor 用来迭代生成多个元素,很常用

举个例子,这个table就是用for迭代出来的,好用:

 

 html:

<table>
    <tr>
        <th>name</th>
        <th>age</th>
        <th>address</th>
    </tr>
    <tr *ngFor="let stu of stus">
        <td>{{stu.name}}</td>
        <td>{{stu.age}}</td>
        <td>{{stu.address}}</td>
    </tr>
</table>

ts:

  stus = [
    {
      name: 'zhangsan',
      age: '20',
      address: 'China Shanghai'
    },
    {
      name: 'lisi',
      age: '20',
      address: 'England london'
    },
    {
      name: 'wangwu',
      age: '20',
      address: 'America NewYork'
    },
    {
      name: 'zhangsan2',
      age: '20',
      address: 'China Xian'
    },
    {
      name: 'zhangsan3',
      age: '20',
      address: 'China Hangzhou'
    },
  ];

css:

table
{
    border-collapse: collapse;
    text-align: left;
}
table td, table th
{
    border: 1px solid #cad9ea;
    color: #666;
    height: 25px;
    padding: 3px;
    text-indent: 3px;
}
table th
{
    text-align: center;
    background-color: #CCE8EB;
    width: 150px;
    padding: 5px;
}
table tr:nth-child(odd)
{
    background: #fff;
}
table tr:nth-child(even)
{
    background: #F5FAFA;
}

 

注:可迭代的不仅仅是原生DOM元素,还包括 Angular组件

 

2. *ngIf 添加或者删除元素

举个例子:

添加元素:

 

删除元素:

 

实现:

<input [(ngModel)]="isShow" type="checkbox">
<div *ngIf="isShow">This is a div element</div>

 

3. *ngSwitch 用来根据各种情况,选择生成特定元素

注:虽然ngSwitch不是一个结构性指令,其实是属性型指令,但是它实现的功能和前面的很类似,所以也放到这里:

 

 

 

 html:

<label><input type="radio" name="type" value="comp1" [(ngModel)]="compType">First Component</label>
<label><input type="radio" name="type" value="comp2" [(ngModel)]="compType">Second Component</label>
<label><input type="radio" name="type" value="comp3" [(ngModel)]="compType">Third Component</label>

<ng-container [ngSwitch]="compType">
    <div *ngSwitchCase="'comp1'">This is Our First Component</div>
    <div *ngSwitchCase="'comp2'">This is Our Second Component--><input></div>
    <div *ngSwitchCase="'comp3'">This is Our Third Component<button>button</button></div>
    <div *ngSwitchDefault>This is default</div>
</ng-container>

 

posted @ 2020-03-22 15:30  内心澎湃的水晶侠  阅读(291)  评论(0编辑  收藏  举报