【发布时间】:2017-07-09 03:20:19
【问题描述】:
我有一个基本的 Angular 应用程序,包含以下 3 个组件:
- car-component 是主组件或父组件。
- carousel-component(car-component 的子组件,*使用 ng-content)
- 子组件(轮播组件的子组件)
子组件内的按钮在单击时使用 EventEmitter() 发出事件。从 plunker 中的代码可以看出,汽车组件(即主组件或主组件)能够监听并捕获其 child 的子组件(即 child -component.ts) 和 {{text}} 在汽车组件模板中更新。
但是,carousel-component 是子组件的直接父级未能捕获相同的事件,并且在 carousel-component 内没有更新任何文本。 p>
car-component.ts
import {Component} from 'angular2/core';
import {CarouselComponent} from './carousel-component';
import {Child} from './child.component';
@Component({
selector: 'my-app',
template: `
<div style="border:1px solid #CCC; padding: 5px; margin: 5px;">
car-comp txt: {{text}}
<carousel-component>
<child (changed)="onChange($event)"></child>
</carousel-component>
</div>
`,
directives : [Child, CarouselComponent]
})
export class CarComponent {
text: string = '?';
onChange(value) {
console.log('car-component onChange fn..');
this.text = value;
}
}
carousel-component.ts
import {Component, EventEmitter} from 'angular2/core';
import {Output} from 'angular2/core';
@Component({
selector: 'carousel-component',
template: `
<div style="background: #CCC; padding: 10px;">
<div>carousel-component txt: {{carouselTxt}}</div>
<ng-content></ng-content>
</div>
`,
})
export class CarouselComponent {
carouselTxt: string = '?';
changed = new EventEmitter();
onChange(value) {
console.log('carousel-comp onChange called..');
this.carouselTxt = value;
}
}
child.component.ts
import {Component, EventEmitter} from 'angular2/core';
import {Output} from 'angular2/core';
@Component({
selector: 'child',
template: `
<div style="background: #FFF; padding: 10px;">
child-comp txt:
<input type ="text" #textInput value="{{txt}}">
<button (click)="onChange(textInput.value)">Emit</button>
</div>
`,
outputs:['changed']
})
export class Child {
txt: string = 'abc';
changed = new EventEmitter();
onChange(value) {
this.txt = value;
this.changed.emit(value);
}
}
谁能告诉我我哪里出错了?
【问题讨论】:
-
有人可以帮我解决这个问题吗?我现在正在使用主题(来自 rxjs)和服务类(@injectable)作为解决方法。无论如何,将不胜感激上述问题的任何建议或解决方案。谢谢。