Angular 2:在父级上未定义ViewChild

时间:2017-06-22 14:30:55

标签: javascript angular

我有以下错误:

  

错误:未捕获(在promise中):TypeError:无法设置undefined的属性'test_id'   TypeError:无法设置未定义的属性'test_id'

错误是在这一行触发:

    console.log('after view init testList', this.productList.test_id);

我看了很多帖子但是所有这些帖子看起来都已经过时了,而且大多数人都说我必须使用我做过的函数ngAfterViewInit。 我有一个触发updateTestId的clic动作,我想将这个id传递给我的子视图ProductListComponent。 这是我的父组件:

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

import {Test,TestData} from './testService';

import { LocalDataSource } from 'ng2-smart-table';
import {ProductListComponent} from '../../components/product/list/productList.component';



@Component({
  selector: 'test-list',
  templateUrl: './testList.html',
  styleUrls: ['./testList.scss']
})
export class TestListComponent{

  //tests: Test[];
  tests: any[];
  selected_test : number;


  @ViewChild(ProductListComponent)
  private productList: ProductListComponent;

  constructor(protected service: TestData){
    this.service.getData().then((data) => {
      this.tests = data.tests;
      this.source.load(data);
    });


  }

  settings = {
    editable : false,
    actions: {
      add:false,
      edit:false,
      delete:false
  },
  columns: {
      id: {
        title: 'ID',
        type: 'number'
      },
      nb_cartons: {
        title: 'Cartons',
        type: 'number'
      },
      nb_items: {
        title: 'Items',
        type: 'number'
      },
      nb_pallets: {
        title: 'Pallets',
        type: 'number'
      },
  };

  //source : Test[];
  source: LocalDataSource = new LocalDataSource();


  public updateTestId(value:any):void {

    this.selected_test = value.data.id;
    console.log('rowSelect', this.selected_test );
    //console.log(this.productList.test_id)

  }


}

这是我的孩子组成部分:

    import { Component,Input,Output, OnChanges, SimpleChanges } from '@angular/core';

import { LocalDataSource } from 'ng2-smart-table';
import {Test} from '../../test/testService';

@Component({
  selector: 'product-list',
  templateUrl: './productList.html',
  styleUrls: ['./productList.scss']
})
export class ProductListComponent implements OnChanges{

  @Input() test_id : number = null;

  settings = {
    editable : false,
    actions: {
      add:false,
      edit:false,
      delete:false
    },
    columns: {
      id: {
        title: 'ID',
        type: 'number'
      },
      sku: {
        title: 'SKU',
        type: 'string'
      },
      reference: {
        title: 'Reference',
        type: 'string'
      },
      size: {
        title: 'Size',
        type: 'string'
      },
    },
    edit: {
      editButtonContent: '<i class="ion-edit"></i>',
      saveButtonContent: '<i class="ion-checkmark"></i>',
      cancelButtonContent: '<i class="ion-close"></i>',
    }
  };

  source: LocalDataSource = new LocalDataSource();


  constructor() {

  }

  ngOnChanges(changes: SimpleChanges) {
    console.log(changes['test_id'],changes['test_id'].currentValue);
    console.log('change in child',changes.test_id);
  }

  /*
  @Input()
  set _test_id(id: number) {
    this._test_id = id;
  }

  get test_id(): number { return this._test_id; }
*/

}

我使用这样的子选择器:

<test-list></test-list>
<product-list #productList [test_id]="selected_test"></product-list>

2 个答案:

答案 0 :(得分:4)

template reference variable名称添加到模板中的product-list

<product-list #productList [test_id]="selected_test"></product-list>

并在组件

中引用它
@ViewChild('productList')
private productList: ProductListComponent;

修改

在这种情况下, Vivek Doshi 在他的答案中是正确的,因为您通过@Input将数据传递给孩子,因此您不需要它。但仍然 - 如果你想使用ViewChild,这是一个解决方案:)

答案 1 :(得分:3)

如果您想将数据从父级传递给子级,则可以直接传递

<product-list [test_id]="selected_test"></product-list>

就是这样,仅此而已。

无需通过@ViewChild

访问它
  

从product-list组件

检测随时间变化的值
ngOnChanges(changes: SimpleChanges) {
    console.log(changes['test_id'].currentValue);
}

示例:

@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements OnChanges {
  @Input()
  prop: number;

  ngOnChanges(changes: SimpleChanges) {
    // changes.prop contains the old and the new value...
  }
}

注意事项: 您需要在子组件上implements OnChanges

有关详情,请参阅此doc