Sur*_*ras 15 components angular
我在角度2中非常新.我在两个组件之间进行通信时遇到问题.当我有一个父项和一些子组件的布局时,可以很容易地使用@Input注释设置子组件的变量.
但是现在我有一个父组件的布局(主要用于布局)和两个子组件:
子组件2有一堆按钮,只创建一个简单的消息.现在我想在子组件1中显示此消息.
我该如何解决?提前致谢
Sei*_*vic 17
除了使用@Input/ @Output和父组件作为"桥" 的解决方案之外,常见的方法也是引入共享服务.该服务需要在父组件中提供,以便子项可以共享单个服务实例(如何在Angular 2中创建单例服务?).
使用BehaviorSubject作为委托的基本示例:
@Injectable()
export class SharedService {
messageSource: BehaviorSubject<string> = new BehaviorSubject('');
constructor() { }
}
Run Code Online (Sandbox Code Playgroud)
子组件1:
export class ChildComponent1 {
constructor(private _sharedService: SharedService) { }
sendMessage(): void {
this._sharedService.messageSource.next('Hello from child 1!');
}
}
Run Code Online (Sandbox Code Playgroud)
子组件2:
export class ChildComponent2 {
constructor(private _sharedService: SharedService) {
this._sharedService.messageSource.subscribe((message: string) => {
console.log('Message: ', message); // => Hello from child 1!
});
}
}
Run Code Online (Sandbox Code Playgroud)
请参阅此文章:Angular2 - 使用服务的组件之间的交互
Fal*_*aly 10
一种简单的方法是在子组件2中将@Output的输出设置为eventemitter,并在单击按钮时发出一个事件,并将消息作为数据传递.然后,在父组件中侦听此事件,并更新在事件发生时设置为子组件1的输入的属性.
下图是一个清楚显示机制的示例
您可以使用模板变量来引用兄弟姐妹:
<child1 #child1></child1>
<child2 (someOutput)="child1.doSomething($event)"></child2>
Run Code Online (Sandbox Code Playgroud)
您可以使用@ViewChild和@Output更新子组件中的属性.
或者你可以用来
@Input代替@ViewChild.
seidme建议的方法也可以正常工作.这取决于您的使用案例.
示例使用@ViewChild和@Output:https:
//plnkr.co/edit/r4KjoxLCFqkGzE1OkaQc?p = preview
使用@Input和https://plnkr.co/edit/01iRyNSvOnOG1T03xUME?p=preview的示例@Output
| 归档时间: |
|
| 查看次数: |
14108 次 |
| 最近记录: |