Angular2 / 4 ngFor指令不允许变量赋值

时间:2017-07-21 21:56:35

标签: angular filter ngfor

在我的AngularJS应用程序中,我曾经在我的HTML模板中执行以下操作:

<tr ng-repeat="user in filtered = (users | filter:searchTerm | orderBy:firstName)">

然后我可以使用变量&#34;过滤&#34;在我的控制器中,以便我可以访问我的过滤表行项目。

Angular 2/4不允许这样的分配,那么我怎样才能在Angular 2/4中做到这一点?

更新:

组件:

export class UsersComponent implements OnInit {
  users = [];
  totalItems = 0;
  filteredUsers = [];
  filteredUser: User;

  constructor(private dataService: DataService) { }

  ngOnInit() {
    this.dataService.getUsers()
    .subscribe(
      (data: any) => {
        this.users = data.data;
      },
      msg => console.error(`Error: ${msg.status} ${msg.statusText}`)
    );
  }

  trackItems(index, item){
    this.totalItems = index+1;
    this.filteredUsers.push(item); // <- This does not work? Should be able to push the item to my filteredUsers array?
    return item ? item.id : undefined;
  }
}

模板:

<tr *ngFor="let user of users | filterBy: ['firstName', 'lastName', 'email']: searchTerm; trackBy: trackItems">

错误讯息:

UsersComponent.html:49 ERROR TypeError: Cannot read property 'push' of undefined
    at DefaultIterableDiffer.webpackJsonp.../../../../../src/app/pages/users/users.component.ts.UsersComponent.trackItems [as _trackByFn] (users.component.ts:108)
    at DefaultIterableDiffer.webpackJsonp.../../../core/@angular/core.es5.js.DefaultIterableDiffer.check (core.es5.js:6857)
    at DefaultIterableDiffer.webpackJsonp.../../../core/@angular/core.es5.js.DefaultIterableDiffer.diff (core.es5.js:6830)
    at NgForOf.webpackJsonp.../../../common/@angular/common.es5.js.NgForOf.ngDoCheck (common.es5.js:1669)
    at checkAndUpdateDirectiveInline (core.es5.js:10837)
    at checkAndUpdateNodeInline (core.es5.js:12330)
    at checkAndUpdateNode (core.es5.js:12269)
    at debugCheckAndUpdateNode (core.es5.js:13130)
    at debugCheckDirectivesFn (core.es5.js:13071)
    at Object.View_UsersComponent_0._co [as updateDirectives] (UsersComponent.html:58)

UsersComponent.html:49 ERROR CONTEXT DebugContext_ {view: Object, nodeIndex: 97, nodeDef: Object, elDef: Object, elView: Object}

2 个答案:

答案 0 :(得分:0)

using Microsoft.Practices.Unity;

namespace ConsoleApp
{
    class Program
    {
        static IUnityContainer container;
        static void Main(string[] args)
        {
            container = new UnityContainer();
            container.RegisterType(typeof(IDataTranslator<>), typeof(IdentityDataTranslator<>));

            IdentityDataTranslator<string> translator = container.Resolve<IDataTranslator<string>>() as IdentityDataTranslator<string>;
            string result = translator.Translate("12351");
        }
    }

    public interface IDataTranslator<TFrom, TTo>
    {
        TTo Translate(TFrom fromObj);
    }

    public interface IDataTranslator<T> : IDataTranslator<T,T>
    {
    }

    public class IdentityDataTranslator<T> : IDataTranslator<T>
    {
        public T Translate(T fromObj)
        {
            return fromObj;
        }
    }
}

我们可以使用trackBy提供自己的机制来跟踪列表中的项目。我们需要将一个函数传递给trackBy,该函数需要一些参数,它们是索引和当前项:

<tr *ngFor="let hero of heroes; let first = first; let last = last" >
//OR
<tr *ngFor="let hero of heroes; let even = even; let odd = odd" >

 //OR
 <tr *ngFor="let hero of heroes; trackBy: trackHero" >

http://blog.angular-university.io/angular-2-ngfor/

答案 1 :(得分:0)

您可以将as*ngIf

一起使用
<ng-container *ngIf="users | filterBy:[...] as filteredUsers">
  <tr *ngFor="let user of filteredUsers">

但这会创造一个&#34;变量&#34; filteredUsers,它是模板的本地,与&#34;控制器&#34;无关。 (另请注意Angular team recommends against filter and sort pipes。)

您无法在模板表达式的上下文中设置控制器属性,例如*ngFor*ngIf中使用的模板表达式。您可以在事件处理程序中设置它,但这是另一种情况:

<my-component (onToggle)="prop = !prop">

一般来说,最好避免在模板中放置太多逻辑。模板应限制在屏幕上显示代表控制器状态的像素所需的内容。当您需要计算某些内容或过滤某些内容时,请在控制器中执行此操作。