例如,我们有两个图像,一个在父组件中,另一个在子组件中。单击子图像可以使父图像更改,这很容易实现。但是如何在点击父图像时更改子图像?
答案 0 :(得分:1)
我会看到几种方法:
@Output
)并触发事件以通知父组件。有关详细信息,请参阅此链接:`Error: Output is not defined` when passing value outside a directive to parent directive 答案 1 :(得分:1)
单击父图像时如何更改子图像?
通常,当父母想要与孩子交流某事时,请使用子输入属性。如果要执行某些逻辑,请实现ngOnChanges()
以在输入属性更改时得到通知:
ngOnChanges(changes) {
console.log(changes);
}
我假设你想在输入属性playBtnStatus
发生变化时在PauseBtnComponent中做一些事情:
ngOnChanges(changes) {
console.log(changes);
if(changes.playBtnStatus.currentValue) { ... }
else { ... }
}
另一种选择是在父组件中使用@ViewChild
,@ViewChildren
或@Query
来获取对子(ren)的引用。然后你可以调用孩子的公共方法。
答案 2 :(得分:0)
你的傻瓜不起作用所以要弄清楚你的具体问题在哪里有点困难。但一般情况并不太难。
如果要在单击子项时更改父项,则只需在子项上使用output
即可。例如,单击此处的子项将替换父项中的图像(working plunk)
import {Component, Output, EventEmitter} from 'angular2/core'
@Component({
selector: "child";
template:`
<div>
<h3> Child Image: </h3>
<img src="{{uri}}" (click)="imageClicked($event)" />
</div>
`
})
export class childComponent {
@Output() wasClicked: EventEmitter<Node> = new EventEmitter();
uri: string = "https://upload.wikimedia.org/wikipedia/commons/e/e5/Элемент_И-НЕ_%28100%29.PNG"
imageClicked(e) {
console.log("child component recieved click" )
this.wasClicked.emit(e)
}
}
@Component({
selector: "parent";
template:`
<div>
<h2> Parent Image: </h2>
<img src="{{uri}}" />
</div>
<child (wasClicked)="childClicked(e)"></child>
`,
directives: [childComponent]
})
export class parentComponent {
switch: boolean = false;
uri: string = "https://upload.wikimedia.org/wikipedia/commons/1/14/Элемент_Исключающее_ИЛИ_%28100%29.png"
childClicked(e){
console.log("parent recieved click event from child")
this.switch
? this.uri = "https://upload.wikimedia.org/wikipedia/commons/1/14/Элемент_Исключающее_ИЛИ_%28100%29.png"
: this.uri = "https://upload.wikimedia.org/wikipedia/commons/7/7a/Элемент_ИЛИ-НЕ_%28100%29.PNG"
this.switch = !this.switch
}
}