2016-10-10 87 views
3

我有以下幾點看法(interests.component.html):Angular2 ViewChild模板

<Tree #tree [nodes]="nodes" [options]="treeOptions"> 
    <template #treeNodeTemplate let-node> 
    <inline-editor #nodeEdit type="text" [(ngModel)]="node.data.name" (onEdit)="beginEditable($event)" (onSave)="saveEditable($event)" name="node{{node.data.id}}" size="8"></inline-editor> 

     <a (click)="addNode(node)"><i class="pull-right btn btn-xs icon-plus"></i></a> 
     <a (click)="editNode(node)"><i class="pull-right btn btn-xs icon-note"></i></a> 
     <a (click)="deleteNode(node)"><i class="pull-right btn btn-xs icon-trash"></i></a> 
    </template> 
</Tree> 

我的組件看起來像這樣(interests.component.ts):

import { Component, ViewChild, ViewChildren, QueryList } from '@angular/core'; 
import * as _ from "lodash"; 
import * as $ from "jquery"; 

import { AppState } from '../app.service'; 
import {TreeModule, TreeNode, TREE_ACTIONS, KEYS, IActionMapping } from 'angular2-tree-component'; 
import {InlineEditorComponent} from 'ng2-inline-editor'; 

@Component({ 
    selector: 'interests', 
    providers: [], 
    styleUrls: ['./interests.component.scss'], 
    templateUrl: './interests.component.html' 
}) 
export class Interests { 
    @ViewChild('tree') tree: any; 
    @ViewChildren('nodeEdit') nodeEdits: any; 

    /** Level multiplikator for tree id creation. */ 
    public static readonly LEVEL_MULTIPLIKATOR = 100000; 

    /** Last inline text element which is/was in edit mode. */ 
    public lastSelectedEditElement: any; 

    /** Id of last selected edit node. */ 
    public lastSelectedEditId: number; 

    /** Options for the tree component. */ 
    treeOptions = { 
    allowDrag: true 
    }; 

    /** contains the tree nodes. */ 
    nodes: any; 

    ngAfterViewInit() { 
    console.log(this.nodeEdits); 
    } 

} 

我想編輯點擊獲得inline-editor以調用編輯功能,但我無法獲得此對象的引用。 我已經試過以下viewChildren:

@ViewChildren('nodeEdit') nodeEdits: any; 

但它始終是不確定的。 獲得treetreeNodeTemplate按預期工作。

希望有人能夠幫助我:)

更新

我嘗試在一個編輯按鈕,點擊所以ngAfterViewInit()之前調用訪問this.nodeEdits

我嘗試從我的興趣控制器訪問它,該控制器是視圖的控制器。

+0

你在哪裏訪問它? – micronyks

+0

添加「未定義」是什麼? 'NgOnInit'? 'NgAfterViewInit'?需要更多的細節。 –

回答

1

您不能在ngOnInit()或構造函數中訪問nodeEdits。只有當ngAfterViewInit()被稱爲this.nodeEdits被設置。

+0

它在ngAfterViewInit中也是未定義的。 –

+0

請添加更多的代碼,使其更加明顯你在做什麼。 HTML在哪裏?@ViewChildren()',... –