【问题标题】:Angular 4 access template element without template local variable没有模板局部变量的Angular 4访问模板元素
【发布时间】:2017-12-04 11:23:17
【问题描述】:

我有一个父组件(比如ParentComponent),我需要向它动态地添加许多子组件(比如ChildComponent1ChildComponent2、...ChildComponentN)。每个组件都不同。

我按照这个来解决我的问题:Angular 2 RC5-6 - Dynamically insert a component

但是为了访问将保存我的ChildComponents 到@ViewChild 的模板元素(一个简单的<div>),我需要在这个<div> 元素上设置一个模板局部变量。

但是,在我的例子中,我不能这样做,因为我不能使用 动态名称 设置模板局部变量。所以我的<div> 元素只有一个动态添加的唯一id 属性(如<div id="child1">)。

有没有什么方法可以通过 typescript 中的组件实现访问我的<div> 元素没有模板局部变量

【问题讨论】:

  • 可以给元素添加指令吗?喜欢<div mydir...?
  • @Maximus 是的,我可以向<div> 添加一个指令(但每个<div> 必须具有独特的内容,以便在右侧ChildComponent 元素下添加正确的ChildComponent 模板)

标签: angular angular-components angular-template


【解决方案1】:

我认为您可以创建一个指令mydir 来公开一个元素:

@Directive({selector: 'mydir'})
export class MyDir {
  @Input('mydir') id;
  constructor(public vc: ViewContainerRef) {

  }
}

然后将其应用到 div:

<div [mydir]="child1">
<div [mydir]="child2">

然后从父组件中查询:

@ViewChildren(MyDir) children;

ngAfterViewInit() {
   const specificID = 'child1';
   const instance = children.find((c)=>{c.id === specificID});
   const vc = instance.vc;
}

【讨论】:

  • 我认为这可行,但@ViewChildren 给了我QueryList&lt;MyDir&gt;。我需要一个ViewContainerRef 才能在&lt;div&gt; 元素下添加我的子组件模板。您对我怎么能有任何想法:1)通过指令通过 id 获取特定的&lt;div&gt; 元素? 2)得到这个特定&lt;div&gt;元素的ViewContainerRef
  • @Dartz,请参阅我的编辑。 @ViewChildren 将为您提供MyDir 的实例,但在每个实例上您都会找到vc,这将是对视图容器的引用
  • 这几乎可以工作,但由于未知原因,调试器显示指令的 id 始终未定义(我对指令不太满意)。我在指令的@Input 行上有一个我的IDE 警告[tslint] In the class "MyDir", the directive input property "id" should not be renamed.Please, consider the following use "@Input() id: string" (no-input-rename)。但是如果我写@Input() id: string;,我会在应用程序加载时出现角度错误Error: Template parse errors: Can't bind to 'mydir' since it isn't a known property of 'div'..
  • @Dartz, tslint 不是问题。你能显示你的代码吗?我不知道你从哪里得到child1child2
  • 当然。 DirectiveTemplateComponent。我在模板中硬编码了 id 以简化调试。
【解决方案2】:

如果你有 angular 4,你可以使用 *ngComponentOutlet="dinamicCompomponent" 动态插入组件

【讨论】:

  • 是的,但我也会遇到同样的麻烦。实际上,我需要在父组件的打字稿中访问子组件才能设置子组件属性(因为ngComponentOutlet 尚不支持@Input@Output)。
  • 在父组件中使用@ViewChild()
  • 但是@ViewChild 需要一个选择器,这是我的问题的重点。
猜你喜欢
  • 1970-01-01
  • 2017-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-14
  • 1970-01-01
  • 2017-07-20
  • 2016-04-03
相关资源
最近更新 更多