David Ericsson
David Ericsson

Reputation: 2660

Class method not working Angular 2 Typescript

I have a <navbar> component, which has a method makeSelected, which as the name says makes an item selected. This works great while clicking on the item, however on my homepage, i want it to be selected without having to click it.

I've injected the Navbar component into my Home component, and in the Home constructor i call the makeSelected method:

import {Component, View} from 'angular2/core';
import {Navbar} from '/app/navbar/navbar';

@Component({
  selector: 'home',
  providers: [Navbar]
})

@View({
  templateUrl: '/app/home/home.html',
  directives: [Navbar]
})

export class Home {

    constructor(public navbar : Navbar) {

      this.navbar = navbar;
      this.navbar.makeSelected('Item 1');

    }

}

The navbar component:

import {Component, View} from 'angular2/core';

@Component({
  selector: 'navbar'
})

@View({
  template: `
  <ul>
    <li *ngFor="#item of items; #i = index" (click)="makeSelected(item.name)">

      {{ item.name }} <div *ngIf=" item.selected == true"> [selected] </div>

    </li>
  </ul>
  `
})

export class Navbar{
  constructor(){
      this.items = [
        {id: 1, name: 'Item 1', href: 'http://www.google.com', selected: false}
      ]
  }
  makeSelected(name)
  {
    for(var i in this.items)
    {
      this.items[i].selected = false;

      if(this.items[i].name == name)
      {
        this.items[i].selected = true;
      }
    }
  }
}

The page displays fine, but the item is not selected. There are no errors, so the method seems to be called.

Why isn't the item selected?

Upvotes: 3

Views: 1508

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202146

You can't inject child components like this into the parent component. You should reference this component using @ViewChild or @Query:

export class Home {
  constructor(@Query(Navbar) children:QueryList<Navbar>) {
    this.navbar = children.first();
    this.navbar.makeSelected('Item 1');
  }
}

Be careful to remove NavBar from the providers property of the component. Keep it only in the directives property.

See this question for more details:

Upvotes: 1

Related Questions