无法读取Angular2 Typescript中未定义的属性“值”

时间:2017-04-26 17:27:50

标签: angular typescript

我正在构建一个Angular2应用,试图通过点击*ngIf

来摆脱div

以下是我的观点:

<router-outlet>

<div class="releasesMenu" *ngIf="detailedInfo">
  <h1>Releases</h1>
  <div class="search">
    <input type="text" #search (keyup)="0" placeholder="Find release by its name, song or year">
  </div>
</div>

<div class="releasesOutlet container">
        <div class="row releasesBlock">
           <div *ngFor="let release of (releases| searchFilter: search.value )" class="releaseRender" (click)="onSelect(release)">
              <div class="releaseRenderWrap" *ngIf="!selectedRelease">
            <span>Something interesting...</span>
          </div>
       </div>

        <div class="releaseDetails" *ngIf="selectedRelease">
          <div class="releaseDetailsWrap">
                <span>Some details...</span>
          </div>
        </div>
      </div>
  </div>
</router-outlet>

这是我的控制器:

import { Component, OnInit } from '@angular/core';
import { SearchFilter } from './../search-filter.pipe';
import { ReleasesService } from '../releases/releases.service';

@Component({
  selector: 'releases-component',
  providers: [ReleasesService],
  templateUrl: './app/releases/releases.component.html',
  styleUrls: ['./app/releases/releases.component.css','./css/grid.css']
})

export class ReleasesComponent implements OnInit { 
  releases: any = [];
  release: any;
  selectedRelease: any;
  private detailedInfo: boolean;

  onSelect(release){
    this.detailedInfo = false;
    this.selectedRelease = release;
    console.log(release)
    }

  constructor(private releasesService: ReleasesService){ }

  ngOnInit(){
    this.releasesService.getReleases()
    .subscribe(data => this.releases = data);
  }

}

我想要的是删除/隐藏.releasesMenu上的(click)="onSelect(release)块。但是我收到了错误: 无法读取未定义的属性“值”

1 个答案:

答案 0 :(得分:3)

那是因为#search位于*ngIf

将此添加到您的组件类

@ViewChild('search')search:ElementRef;

并将*ngFor更改为

*ngFor="let release of (releases| searchFilter: search?.nativeElement?.value )"

另见Angular2, *ngIf and local template variables