Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 结构指令能否使用@ContentChild引用子组件?_Angular_Angular Directive_Angular Components - Fatal编程技术网

Angular 结构指令能否使用@ContentChild引用子组件?

Angular 结构指令能否使用@ContentChild引用子组件?,angular,angular-directive,angular-components,Angular,Angular Directive,Angular Components,如果我有一个自定义指令ParentDirective和自定义组件ChildComponent这样排列: <div appParent> <app-child></app-child> </div> 看看这是怎么回事。(它登录到控制台以显示子成员已设置) 但是,如果我将appParent更改为结构指令,则永远不会设置子成员 <div *appParent> <app-child></app-child>

如果我有一个自定义指令
ParentDirective
和自定义组件
ChildComponent
这样排列:

<div appParent>
  <app-child></app-child>
</div>
看看这是怎么回事。(它登录到控制台以显示
子成员已设置)

但是,如果我将appParent更改为结构指令,则永远不会设置
子成员

<div *appParent>
  <app-child></app-child>
</div>


是否不能将
@ContentChild
与结构指令一起使用?

我认为您不能,这是由于angular对这两种指令使用的设计。通过
TemplateRef
创建指令,并通过
ViewContainerRef
createEmbeddedView
注入指令,将模板生成为dom中的同级,而不是子级。因此,Angular的注射也尊重这一点,这样孩子和造物的地方就看不见对方了。你可以在脑海中画一个额外的图层

createEmbeddedView

  createEmbeddedView(context: any): EmbeddedViewRef<any> {
    return new ViewRef_(Services.createEmbeddedView(
        this._parentView, this._def, this._def.element !.template !, context));
  }

createEmbeddedView(context:any):EmbeddedViewRef

我在手机上,所以我无法测试,但它对ViewChild有效吗?@IngoBürk:不。你希望它能吗?据我所知,
@ViewChild
允许直接访问组件视图中的组件,而不是其中呈现的内容。我想这可能是因为结构指令本身会分解到模板中,在我看来,子对象更像是视图子对象,而不是内容子对象。不过看来你现在已经有答案了。谢谢你。这并不是我想要的答案,但很高兴知道。
  createEmbeddedView(context: any): EmbeddedViewRef<any> {
    return new ViewRef_(Services.createEmbeddedView(
        this._parentView, this._def, this._def.element !.template !, context));
  }