繁体   English   中英

如何不渲染 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>

这是一个 StackBlitz演示了这种方法。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM