简体   繁体   English

我是否总是必须在angular2中声明变量才能获得更改?

[英]Do I always have to declare a variable in angular2 to get changes?

I have the following code: 我有以下代码:

This is the HTML view: 这是HTML视图:

<button type="button" (click)="filterIt('male')">Filter male gender</button>
     <table>
       <ng-container *ngFor="let item of array;let i=index">
       <tr class="border-bottom" *ngIf="item.condition==condition_var">
         <td>{{i+1}}</td>
         <td>{{item.condition}}</td>
       </tr>
     </ng-container>
</table>

This is the typescript file (.ts): 这是打字稿文件 (.ts):

  condition_var:string;
   filterIt(value){
     this.condition_var=value;
  }

NOTE: the array variable is already populated. 注意:已填充数组变量。 (array of objects: [{}] ) (对象数组: [{}]

My question is: Is it a practice in angular2 to always declare variables and to work with them in expressions, ngIf, ngFor etc. Or can I use a better way rather than populating my class with too many variables which doesn't look good. 我的问题是:在angular2中总是声明变量并在表达式,ngIf,ngFor等中使用它们是一种练习吗?或者我可以使用更好的方法而不是用太多不太好的变量填充我的类。

To be more specific, is there a better way to write this code? 更具体地说,是否有更好的方法来编写此代码?

Yes there is a better (more idiomatic) way to do this: use a @Pipe . 是的,有更好的(更惯用的)方法: 使用@Pipe

import { Pipe, PipeTransform } from "@angular/core";

@Pipe({ name: 'filter' })
export class FilterPipe implements PipeTransform {
  transform(values: any, condition: any): any {
    return values.filter(item => item.condition === condition);
  }
}

Implement with: 实施:

<ng-container *ngFor="let item of array | filter:condition">

And set the condition however you like. 然后根据自己的喜好设定condition Note that filters can accept more than one positional parameter, separated by colons. 请注意,过滤器可以接受多个位置参数,以冒号分隔。

Remember to add the pipe to whichever @NgModule s you use the pipe in: 请记住将管道添加到您使用管道的@NgModule中:

import { FilterPipe } from 'pipes/fitler.pipe.ts';

@NgModule({
  declaractions: [
    FilterPipe
  ],
  // ...
})

And if the @NgModule in question is a lazy-loaded "shared" module, don't forget to re-export it: 如果有问题的@NgModule是一个延迟加载的“共享”模块,请不要忘记重新导出它:

@NgModule({
      declaractions: [
        FilterPipe
      ],
      exports: [
        FilterPipe
      ],
      // ...
    })

This answer is currently valid as of angular 4.3.6 . 这个答案目前在角度4.3.6有效。

I would use a getter inside your component class which filters the array you're looping over. 我会在你的组件类中使用一个getter来过滤你正在循环的数组。 Like this: 像这样:

public myArray: any[] = [];
public myCondition: string | null = null;

public get myFilteredArray() {
  return this.myArray.filter(item => item.condition === this.myCondition);
}

And in your template just use the filteredArray: 在您的模板中,只需使用filteredArray:

<table>
  <tr class="border-bottom" *ngFor="let item of myFilteredArray;let i=index">
    <td>{{i+1}}</td>
    <td>{{item.condition}}</td>
  </tr>
</table>

Or you could build a pipe for it: 或者你可以为它构建一个管道:

@Pipe({ name: 'myFilterPipe' })
export class MyFilterPipe implements PipeTransform {
  transform(value: any[], condition: string | null): any[] {
    if(!Array.isArray(value)) return [];
    return value.filter(item => item.condition === condition);
  }
}

In your case, you are filtering the data based on "male" string. 在您的情况下,您将基于“男性”字符串过滤数据。

So you can directly use the following snippets: 因此,您可以直接使用以下代码段:

*ngIf="item.condition=='male'"

don't need to make function, it will handle in if block , 不需要生成函数,它会在if块中处理,

I would solve it this way: 我会这样解决:

//YOUR COMPONENT .TS CODE
filterIt(parameter: String){
//filter this.array here using your parameter
}

//YOUR COMPONENT .HTML CODE
<button type="button" (click)="filterIt('male')">Filter male gender</button>
 <table>
   <ng-container *ngFor="let item of array;">
   <tr class="border-bottom">
     <td>{{i+1}}</td>
     <td>{{item.condition}}</td>
   </tr>
 </ng-container>

This is much cleaner and let's the logic happen in your.ts file while your web page only displays. 这更清晰,让你的网页只显示在你的.ts文件中。

Here is an approach if you want to avoid declaring the variable in your class. 如果您想避免在类中声明变量,这是一种方法。 Just initialize variable on button click: 只需在按钮点击时初始化变量:

<button type="button" (click)="condition = 'male'">Filter male gender</button>
<table>
    <ng-container *ngFor="let item of array;let i=index">
        <tr class="border-bottom" *ngIf="item.condition == condition">
            <td>{{i+1}}</td>
            <td>{{item.condition}}</td>
        </tr>
    </ng-container>
</table>

You don't have to declare condition , condition_var or filterIt() method in your class in this way. 您不必以这种方式在类中声明conditioncondition_varfilterIt()方法。 Link to Plunker Demo . 链接到Plunker演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM