[英]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. 我有一个
<navbar>
组件,它有一个方法makeSelected
,正如名称makeSelected
,选择了一个项目。 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: 我已经将Navbar组件注入到我的Home组件中,并在Home构造函数中调用了
makeSelected
方法:
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? 为什么不选择该项目?
You can't inject child components like this into the parent component. 您不能将这样的子组件注入父组件。 You should reference this component using
@ViewChild
or @Query
: 您应该使用
@ViewChild
或@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. 小心从组件的
providers
属性中删除NavBar
。 Keep it only in the directives
property. 仅将其保留在
directives
属性中。
See this question for more details: 有关详细信息,请参阅此问题:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.