我正在玩angular2。我使用名为appmenu的angular cli创建了1个组件。
appmenu.html如下:
<ul>
<li (click)="menuitem1()">Menu Item 1</li>
<li>Menu Item 2</li>
<li>Menu Item 3</li>
</ul>
我希望在app.component.html上获取testvariable
的值,但我不知道我应该在app.component.ts
appmenu.ts as follows
import { Component, OnInit } from '@angular/core';
import { Injectable } from '@angular/core';
@Component({
providers: [AppMenuService], // GIVING ERROR HERE
selector: 'app-appmenu',
templateUrl: './appmenu.component.html',
styleUrls: ['./appmenu.component.css']
})
export class AppmenuComponent implements OnInit {
public testvariable = "1st";
public data: any;
// constructor(private sharedData: AppMenuService) { }
ngOnInit() {
// this.data = this.sharedData.data;
// console.log(this.data);
}
menuitem1(){
console.log("Menu item 1 clicked");
}
}
appmenu.service.ts
import { Injectable } from '@angular/core';
@Injectable()
export class AppMenuService{
public data: any;
constructor() {
this.data = 'Lorem ipsum dolor sit.';
}
}
此处appmenu.component.ts
收到错误 - &gt; providers: [AppMenuService]
,它说无法找到名称AppMenuService
答案 0 :(得分:0)
您可以在父组件中使用@ViewChild注释:
@ViewChild(AppmenuComponent) appComponent: AppmenuComponent;
https://angular.io/docs/ts/latest/cookbook/component-communication.html
答案 1 :(得分:0)
如果要在两个组件之间静态共享变量,可以在某些服务中声明此变量,并通过注入此服务来使用此变量。 E.g。
// shared-data.service.ts
export class SharedDataService {
public data: any;
constructor() {
this.data = 'Lorem ipsum dolor sit.';
}
}
// app.component.ts
@Component({ ... })
export class AppComponent implements OnInit {
public data: any;
constructor(private sharedData: SharedDataService) { }
public ngOnInit() {
this.data = this.sharedData.data;
}
}
// app-menu/app-menu.component.ts
@Component({ ... })
export class AppMenuComponent implements OnInit {
public data: any;
constructor(private sharedData: SharedDataService) { }
public ngOnInit() {
this.data = this.sharedData.data;
}
}
但通常当您需要在父组件和子组件之间共享某些数据时,您需要使用@Input
和@Output
。 @Input
允许您将数据直接传递给子组件/指令。 @Output
允许您监听子组件的事件。了解详情here。
E.g。
// app.component.ts
@Component({
template: `
<app-menu
[someData]="dataForChild"
(menuClick)="handleMenuClick($event)">
</app-menu>
`
})
export class AppComponent implements OnInit {
public dataForChild: any;
constructor() { }
public ngOnInit() {
this.dataForChild = 'Lorem ipsum dolor sit.'
}
public handleMenuClick(itemIndex) {
console.log(itemIndex);
}
}
// app-menu/app-menu.component.ts
@Component({
selector: 'app-menu',
template: `
<ul>
<li (click)="transferMenuClick(1)">Menu item 1</li>
<li (click)="transferMenuClick(2)">Menu item 2</li>
<li (click)="transferMenuClick(3)">Menu item 3</li>
</ul>
`
})
export class AppMenuComponent implements OnInit {
@Output('menuClick')
public menuClick: EventEmitter<number>;
@Input('someData')
public someData: any;
constructor(private sharedData: SharedDataService) {
this.menuClick = new EventEmitter<number>;
}
public ngOnInit() {
console.log(this.someData);
}
public transferMenuClick(itemIndex) {
this.menuClick.emit(itemIndex);
}
}