父变量在ng-content内部不起作用 [英] Parent variable not working inside of ng-content
问题描述
简介:我正在研究结构如下的ng2组件:
Intro: I'm working on ng2 components whose structure looks like this:
<cards>
<card>
<card-content-type-1 (state)="cardState"></card-content-type-1>
</card>
<card>
<card-content-type-2 (state)="cardState"></card-content-type-2>
</card>
<card>
<card-content-type-3 (state)="cardState"></card-content-type-3>
</card>
...
</cards>
然后我根据click/mouseenter/mouseleave事件更改每个<card>
的状态,并且当<card>
组件(父组件)内部发生某些操作时,我想根据当前状态进行触发<card-content-type-N>
组件(子组件)中的一些动画方法.对于动画序列,我将使用AnimationBuilder
和ElementRef
.
And I'm changing states of each <card>
based on click/mouseenter/mouseleave events, and when some action happen inside of <card>
component (parent component), based on current state, I'd like to trigger some animation methods inside <card-content-type-N>
components (children component). For sequence of animations I'll use AnimationBuilder
and ElementRef
.
问题:我决定将父组件变量传递给子组件,并在子组件内部实现ngOnChanges()
,这将触发取决于当前变量值的特定动画.但是当我在父模板中使用ng-content时,我很难将父变量传递给子代.
Issue: I decided to pass parent component variable to children component, and to implement ngOnChanges()
inside of children, which will trigger specific animation depends of current variable value. But I have troubles to pass parent variable to children when I use ng-content inside of parent template.
我创建了简化示例(我将<card>
替换为<parent-comp>
,并将<card-content-type-N>
替换为<child-comp>
): https://plnkr.co/edit/OHIJjMwdx6ifRiSxsanB?p=preview
I created simplified example (I replaced <card>
with <parent-comp>
, and <card-content-type-N>
with <child-comp>
): https://plnkr.co/edit/OHIJjMwdx6ifRiSxsanB?p=preview
在此示例中,parentVar
没有传递到child-comp
中.这是Angular2中的某个错误,还是我做错了什么?我想这与ng-content
范围有关,但是我们缺乏有关此的好的文档/示例.
In this example parentVar
is not passed into the child-comp
. Is this some bug in Angular2 or I'm doing something wrong? I suppose that is related with ng-content
scope, but we lack good docs/examples about this.
在src/parent-comp.ts
内部的同一示例中,如果我们用<child-comp [childVar]="parentVar"></child-comp>
替换初始模板,则父变量正确传递.
In same example inside of src/parent-comp.ts
if we replace intial template with <child-comp [childVar]="parentVar"></child-comp>
parent variable is passed properly.
在src/app.ts
内,如果我们用以下内容替换初始模板:
Also inside of src/app.ts
if we replace initial template with this:
<parent-comp>
<child-comp [childVar]="true"></child-comp>
</parent-comp>
静态变量正确传递.
有人有类似的问题吗?还是有办法解决这个问题?
Does someone have a similar issue? Or have idea how I can solve this issue?
推荐答案
您可以尝试执行以下操作:
You can try something like this:
<parent-comp #parent>
<child-comp [childVar]="parent.parentVar"></child-comp>
</parent-comp>
这是plunkr https://plnkr.co/edit/rVMruocy2Mhtl4yTmvio?p=preview
这篇关于父变量在ng-content内部不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!