从传递给的组件(我不知道实例类)中获取组件。

huangapple go评论118阅读模式
英文:

Get the component (of which I don't know the instance class) from the one passed to <ng-content>

问题

以下是翻译好的部分:

我有这个组件:

@Component({
selector: 'my-container',
template: `
    <div class="my-container">
        <div #wrapper class="my-container-body">
            <ng-content></ng-content>
        </div>
        <div class="my-container-footer"></div>
    </div>  
`
})
export class MyContainer implements AfterViewInit {
    @ViewChild('wrapped') item: ElementRef;

    ngAfterViewInit() {
        console.log('wrapped item is: ' + this.item.nativeElement);
    }
}

例如,他们可以这样使用我的包装:

<my-container>
    <some-component></some-component>
<my-container>

正如你所看到的,我可以使用@ViewChild来访问包装的组件。但是,我想访问传递给<ng-content></ng-content>的组件实例,但也许这不起作用,因为我不知道要使用的正确类型,因为我不知道传递给我的包装的组件是什么类型。对于@ContentChild也是一样的情况。

我做错了什么吗?如何访问传递的任何组件的属性和方法?

英文:

I have this component:

@Component({
selector: &#39;my-container&#39;,
template: `
    &lt;div class=&quot;my-container&quot;&gt;
        &lt;div #wrapper class=&quot;my-container-body&quot;&gt;
            &lt;ng-content&gt;&lt;/ng-content&gt;
        &lt;/div&gt;
        &lt;div class=&quot;my-container-footer&quot;&gt;&lt;/div&gt;
    &lt;/div&gt;  
`
})
export class MyContainer implements AfterViewInit {
    @ViewChild(&#39;wrapped&#39;) item: ElementRef;

    ngAfterViewInit() {
        console.log(&#39;wrapped item is: &#39; + this.item.nativeElement);
    }
}

For example they can use my wrapped in the following way:

&lt;my-container&gt;
    &lt;some-component&gt;&lt;/some-component&gt;
&lt;my-container&gt;

As you can see I can access to wrapped component, using @ViewChild.
Instead I would like to access to the component instance that is passed to &lt;ng-content&gt;&lt;/ng-content&gt;, but maybe it couldn't work because I don't know what is the right type to use since I don't know what kind of component is passed to my wrapper.
The same occurs with @ContentChild.

Am I doing something wrong? How to access to properties and methods of the passed component that could be any component?

答案1

得分: 1

@ContentChild(NgControl) wrappedControl: NgControl;

英文:

As you need something exact from the content component (in your case it is a NgControl) it would be more logical to query for control, not the whole component.

@ContentChild(NgControl) wrappedControl: NgControl;

huangapple
  • 本文由 发表于 2023年3月9日 17:58:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75682983.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定