美文网首页web前端
angular-语法糖*ngFor

angular-语法糖*ngFor

作者: 姜治宇 | 来源:发表于2020-11-27 16:26 被阅读0次

我们在遍历时经常使用*ngFor,实际上这是个语法糖,实际执行的过程是:
1、创建ng-template标签。
2、在标签上使用[ngForOf]指令。
也就是说,ng-template标签是无法使用*ngFor语法糖的,如果你在遍历时必须使用ng-template标签,那只能这么写:
html文件:

<ul>
    <ng-template ngFor let-item let-i="index" [ngForOf]="listData.list">
        
        
            <li [ngSwitch]="item.role">
                ID:{{i}}
                <span *ngSwitchCase="'admin'">
                    管理员:<input type="text"  [(ngModel)]="item.name" style="background:red;" />
                
                </span>

                <input type="text" *ngSwitchCase="'user'" [(ngModel)]="item.name" />
            </li>
       
        
        
    </ng-template>
</ul>


ts文件:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-loop',
  templateUrl: './loop.component.html',
  styleUrls: ['./loop.component.scss']
})
export class LoopComponent implements OnInit {
  listData = {
    list: [
      { id: 1, name: 'jack', role: 'admin' },
      { id: 2, name: 'tom', role: 'user' },
      { id: 3, name: 'marry', role: 'user' }
    ]
  }
  constructor() { }

  ngOnInit(): void {
  }

}

相关文章

网友评论

    本文标题:angular-语法糖*ngFor

    本文链接:https://www.haomeiwen.com/subject/mumxwktx.html