Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 ViewChild in template

I have the following view (interests.component.html):

<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>

My component looks like this(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);
  }

}

I want to get the inline-editor on an edit click to call an edit function, but I'm not able to get a ref to this object. I've tried the following viewChildren:

@ViewChildren('nodeEdit') nodeEdits: any;

But it is always undefined. To get the tree or treeNodeTemplate works as expected.

Hope somebody is able to help me :)

Update

I try to access this.nodeEdits on an edit button click so ngAfterViewInit() is called before that.

I try to access it from my Interest controller which is the controller for the view.

like image 219
blacksheep_2011 Avatar asked Oct 30 '22 18:10

blacksheep_2011


1 Answers

You can't access nodeEdits in ngOnInit() or the constructor. Only when ngAfterViewInit() is called this.nodeEdits is set.

like image 145
Günter Zöchbauer Avatar answered Nov 11 '22 11:11

Günter Zöchbauer