Angular:如何访问ng-template中的参考变量 [英] Angular: how do I access the reference variable which is in a ng-template

查看:1347
本文介绍了Angular:如何访问ng-template中的参考变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以访问在ng-template元素内声明的#interface?

Is there a way to access #interface, which is declared inside ng-template element?

我必须将< interface-settings放在< ng-template内.

I must put the <interface-settings inside <ng-template.

因为我需要使用* ngTemplateOutlet.

Because I would need to use the *ngTemplateOutlet.

由于找不到解决方案,因此必须添加另一个< interface-settings #interface,并且不要在ng-template中声明它.

As I could not find a solution for this, I have to add another <interface-settings #interface and not declare it inside ng-template.

如果您知道其他解决方法,将不胜感激.谢谢

would appreciate if you know other workaround. Thanks

 //  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");
 }

Angular使用

推荐答案

ng-template进行模板制作-除非某些条件告诉Angular在实际DOM中使用它,否则它不会在DOM中呈现.

ng-template is used by Angular for templating - meaning it is not rendered in DOM unless certain conditions tell Angular to use it in the actual DOM.

因此,当您拥有组件界面设置"时,在ng-template内部-除非:除非您的应用程序无法访问/

So when you have your component "interface-setting" inside ng-template - it is not accessible/known by your application unless:

  • 应用了ng-template条件,并且
  • 您的主机(父)组件具有对它的引用:

例如,类似于您的示例:

For instance, similar to your example:

<button type="button" (click)="hello.sayHello()">Method Inside Hello</button>

<ng-template>
  <hello #hello></hello>
<ng-template>

由于不满足上述2个条件,因此上述内容无法单独使用.要解决此问题,您需要使用ViewChild来获取对hello组件的引用.像这样:

The above on its own won't work as 2 conditions mentioned above are not met. To fix you need to use ViewChild to get reference to the hello component. Like so:

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中):

Then you need to make sure the ng-template is used (whatever triggers the ng-template to be placed in DOM for your app):

<ng-template [ngIf]="true">
  <hello #hello></hello>
<ng-template>

现在,对子组件内部方法的引用将起作用:

Now the reference to the method inside child component will work:

https://stackblitz.com/edit/angular-ivy-hnmw17?file=src/app/app.component.html

您可以了解更多有关Angular的结构指令如何使用ng-template的信息: https://angular .io/guide/structural-directives

You can read more how Angular's structural directives under the hood use ng-template: https://angular.io/guide/structural-directives

这篇关于Angular:如何访问ng-template中的参考变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆