如何不呈现 ViewChild 元素而是在父组件中访问它?

How do I not render ViewChild element but access it in the parent component instead?

我有一个组件在另一个组件中像这样使用:

<inline-help>
            <help-title>{{::'lang.whatIsThis'|i18n}}</help-title>
            <help-body i18n="lang.helpBody"></help-body>
</inline-help>

inline-help 中,我使用 @ViewChild 和 ng-content 来显示 help-titlehelp-body

@Component({
    selector: 'inline-help',
    template: `
<div class="inline-help">
    <div class="help-icon">
        <i class="en-icon-help"></i>
    </div>
    <div #helptext class="inline-help-text text-left">
<ng-content select="help-title"></ng-content>       
<ng-content select="help-body"></ng-content>
    </div>
</div>`
})

export class InlineHelpComponent implements AfterViewInit {

    @Input() fixed: boolean;
    @ViewChild('helptext', {static: false}) text: ElementRef;
......

我想做的是创建一个像 <inline-help-content> 这样的新组件,我可以在里面使用它 :

@Component({
    selector: 'inline-help',
    template: `
<div class="inline-help">
    <div class="help-icon">
        <i class="en-icon-help"></i>
    </div>
    <inline-help-content [helpTitle]="something" [helpBody]="something"></inline-help-content>
</div>`
})

但是我不要想要更改

的所有实例
<inline-help>
            <help-title>{{::'lang.whatIsThis'|i18n}}</help-title>
            <help-body i18n="lang.helpBody"></help-body>
</inline-help>

我在代码库的其他部分使用了它,因为它很多。是否可以解析 ViewChild 然后获取其中的文本并将文本作为输入调用另一个组件?

在您的 InlineHelpComponent 模板中,您可以将 <ng-content> 包装在分配给它们的模板引用变量的元素中:

<div #helpTitle><ng-content select="help-title"></ng-content></div>
<div #helpBody><ng-content select="help-body"></ng-content></div>

这些模板引用变量使您可以访问本机元素,因此您可以将这些元素的 innerText 属性传递到新的 InlineHelpContentComponent(只需确保将投影内容隐藏在InlineHelpComponent 所以它不会显示两次)。 InlineHelpComponent 模板如下所示:

<div class="inline-help">
  <div style="display:none;">
    <div #helpTitle><ng-content select="help-title"></ng-content></div>
    <div #helpBody><ng-content select="help-body"></ng-content></div>
  </div>
  <inline-help-content
    *ngIf="showInlineHelpContent"
    [helpTitle]="helpTitle.innerText"
    [helpBody]="helpBody.innerText">
  </inline-help-content>
</div>

Here's a StackBlitz 展示了这种方法。

我发现我必须在 inline-help-content 组件上包含 *ngIf="showInlineHelpContent",并在 setTimeout 之后在 ngAfterContentInit 中设置标志,否则我会得到一个 ExpressionChangedAfterItHasBeenCheckedError错误。