Angular - `ng-content`无法访问宿主组件?

3
我是一名有用的助手,可以为您翻译文本。
简化:
我的app-root元素具有以下模板:
(以下为需要翻译的内容)
 <div *ngFor="let item of [1,2,3,4,5,6]">
      <card *appDelay="100 * item" [num]="item">
        {{item}}
      </card>
    </div>

它使用结构性指令来完成所有工作。

Plunker:使用appDelay创建带有延迟和顺序号的动态组件。

它使用this.viewContainerRef.createEmbeddedView实现。

但是现在(为了学习目的),我不想使用{{item}},而是通过@input属性numitem发送到card

enter image description here

显然,我已经添加了。
  @Input()
  num : number = 0;

将文本添加到CardComponent组件中,并在createEmbeddedView方法中添加上下文:

 this.viewContainerRef.createEmbeddedView(this.templateRef,{$implicit: {num: time} });

问题

看起来我正在尝试通过两个方向来实现:

1)从上下文到模板
2)@input 变量

但是都不起作用。(我看不到数字。)

我该如何设置数字(使用上下文或 @input)?

Plunker


即使输入不起作用,我也希望显示“0”。 - isherwood
@isherwood https://plnkr.co/edit/80AGn8bR4CiyH0ceP8ws?p=preview - 这是一个适用于数字的示例,但不符合我在问题中想要的。 - Royi Namir
2个回答

2
<card *appDelay="500 * item; let num">
   {{num}}
</card>

等价于

<ng-template [appDelay]="500 * item" let-num="$implicit">
  <card>
       {{num}}
  </card>
</ng-template>

并且内部指令

this.viewContainerRef.createEmbeddedView(this.templateRef,{$implicit:time/500 });

Plunker Example


我不会重复相同的答案。(即:像往常一样,非常感谢。) :-) - Royi Namir
除此之外 - 如果我想向appDelay发送2个参数怎么办?在这里,您发送一个值并将其分成数字。如果我只想发送一个额外的任意数字呢? - Royi Namir
2
num in [num]="item" is not template variable. it's @Input, you can't access to it inside template. Only through component instance that i got via template reference variable #cardComp - yurzui
只有现在我才看到这个:appDelayNum,它是 appDelay__X__。哇! - Royi Namir
让我们在聊天中继续这个讨论。点击此处进入聊天室 - Royi Namir
显示剩余3条评论

1
好的,这是我会做的事情:

https://plnkr.co/edit/Qw9RFNWz18B9UQ6PWRfD?p=preview

  1. 您将模板作为内容发送到卡片组件中。使用ng-template
  2. 在卡片组件中,使用@ContentChild获取对该模板的引用。
  3. 使用ng-container[ngTemplateOutlet]在卡片组件中呈现您的模板。
  4. 要使输入“num”可用于模板,请使用[ngTemplateOutletContext]并将变量$implicit设置为num,($implicit允许您在模板上使用任何变量名称,例如 let-yourVariableName)。
  5. 在您的模板中添加let-num以引用模板上下文变量。
  6. 使用{{num}}打印它。

希望这可以帮助您 :)

抱歉无法使代码内联工作 :/


1
可以运行,但我的代码有什么问题?顺便说一下,我注意到你的解决方案中模板的上下文是多余的(我已经将其删除了,但仍然可以运行)。 - Royi Namir
您正在使用的{{num}}是指当前组件“main”中的内容。通过使用模板,它会在card-component内呈现/实例化,并使用let-num获取该变量。 - Johan Kvint

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接