Angular:如何访问 ng-template 中的引用变量 [英] Angular: how do I access the reference variable which is in a ng-template
问题描述
有没有办法访问#interface,它在ng-template元素中声明?
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");
}
推荐答案
ng-template 被 Angular 用于模板化 - 这意味着它不会在 DOM 中呈现,除非某些条件告诉 Angular 在实际的 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屋!