【问题标题】:Querying Typescript array collection based on key in an Angular HTML component基于Angular HTML组件中的键查询Typescript数组集合
【发布时间】:2017-11-22 19:42:22
【问题描述】:

我刚刚开始使用 Angular 2 和 TypeScript。

我想在表格中显示数据。我要显示的值之一是另一个表的 Id(键)。我不想显示 Id,而是想显示它的名字。

搜索我在这个 SO 问题中找到了如何在 TypeScript 中执行此操作:Querying Typescript array collection based on key

我已复制第一个答案并将其添加到我的 html 组件中:

<div class="col-md-1">{{codeTypes.find(c => c.codeTypeId == level.codeType)[0].name}}</div>

但我收到{{ 的语法错误。如果我删除 {{}} 我只会在 html 中看到:

codeTypes.find(c => c.codeTypeId == level.codeType)[0].name

codeTypes 是 TS 类中的公共属性:

public codeTypes: ICodeType[];

ICodeType 被声明为:

export interface ICodeType {
    codeTypeId: number;
    name: string;
}

我想查询codeTypes 数组以搜索具有相同codeTypeId 的数组并显示其name。如何在 HTML 组件中执行此操作?

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    你不能在 Angular 模板语法中做同样的事情,因为它不等同于 javascript,而是它的一个子集;事实上,不允许使用 lambda,因为它们可能与插值语法({} - 花括号)发生冲突。尝试使用Pipe 或调用组件类中的方法来进行查询,而不是在模板中进行。我强烈建议使用管道

    使用方法:

    queryArray() {
       return this.codeTypes.find(c => c.codeTypeId == this.level.codeType)[0].name
    }
    

    在html中:

    <div class="col-md-1">{{ queryArray() }}</div>
    

    【讨论】:

    • 它有效。谢谢。我没有想过用一种方法来做到这一点。
    【解决方案2】:

    您可以使用管道来实现这一点。

    HTML:

    <table class="table table-responsive table-hover">
     <tr>
      <th>District</th>
     </tr>
     <tr *ngFor="let item of records | slice:0:5 | category: searchText">
      <td>{{item.DistrictName}}</td>
     </tr>
    </table>
    <input type="text" [(ngModel)]="searchText" class="form-control"
    placeholder="Search By Id" />
    

    category.pipe.ts

    import { Pipe, PipeTransform } from '@angular/core';
    @Pipe({ name: 'category' })
    
    export class CategoryPipe implements PipeTransform {
      transform(categories: any, searchText: any): any {
        if(searchText == null) return categories;
    
        return categories.filter(
          function(category){
           return category.id.toLowerCase().indexOf(searchText.toLowerCase()) > -1;
          }
        )
      }
    }
    

    在打字稿文件中包含管道

    import {CategoryPipe} from './category.pipe';
    
    
    and then
    export class CheckListComponent implements OnInit {
    records: Array<any>;
    this.records= [
    { DistrictName: "Ariyalur", id: "1" },
    { DistrictName: "Chennai", id: "2" },
    { DistrictName: "Coimbatore", id: "3" },
    { DistrictName: "Cuddalore",  id: "4" },
    { DistrictName: "Dharmapuri", id: "5" },
    { DistrictName: "Dindigul", id: "6" },
    { DistrictName: "Erode", id: "7" },
    ];
    

    并且在 app.module.ts 中必须声明

    import {CategoryPipe} from './category.pipe';
    
    
    @NgModule({
    declarations: [
    AppComponent,
    CategoryPipe
    ],
    

    【讨论】:

    • 我强烈建议使用管道
    猜你喜欢
    • 2016-10-25
    • 2014-03-03
    • 1970-01-01
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-10
    相关资源
    最近更新 更多