gpt4 book ai didi

angular7 - 角 : how do I access the reference variable which is in a ng-template

转载 作者:行者123 更新时间:2023-12-04 09:13:34 24 4
gpt4 key购买 nike

有没有办法访问在 ng-template 元素中声明的#interface?
我必须把 因为我需要使用 *ngTemplateOutlet。
由于我找不到解决方案,我必须添加另一个 如果您知道其他解决方法,将不胜感激。谢谢

 //  parent.html
<button type="button" (click)="interface.apply()"></button>

<ng-template>
<interface-settings #interface></interface-settings>
<ng-template>
 //child.ts (interface-settings.ts)

apply() {
console.log("apply");
}

最佳答案

ng-template 被 Angular 用于模板化——这意味着它不会在 DOM 中呈现,除非某些条件告诉 Angular 在实际的 DOM 中使用它。
因此,当您在 ng-template 中有组件“接口(interface)设置”时 - 您的应用程序无法访问/知道它,除非:

  • 应用了 ng-template 条件和
  • 您的主机(父)组件有对其的引用:

  • 例如,类似于您的示例:
    <button type="button" (click)="hello.sayHello()">Method Inside Hello</button>

    <ng-template>
    <hello #hello></hello>
    <ng-template>
    由于不满足上述两个条件,上述内容本身不起作用。要解决此问题,您需要使用 ViewChild 来获取对 hello 组件的引用。像这样:
    import { Component, ViewChild } from '@angular/core';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: [ './app.component.css' ]
    })
    export class AppComponent {

    @ViewChild('hello') hello;

    }
    然后你需要确保使用了 ng-template(无论什么触发 ng-template 被放置在你的应用程序的 DOM 中):
    <ng-template [ngIf]="true">
    <hello #hello></hello>
    <ng-template>
    现在对子组件内部方法的引用将起作用:
    https://stackblitz.com/edit/angular-ivy-hnmw17?file=src/app/app.component.html
    您可以阅读更多 Angular 的结构指令如何在后台使用 ng-template: https://angular.io/guide/structural-directives

    关于angular7 - 角 : how do I access the reference variable which is in a ng-template,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63310432/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com