![](/img/trans.png)
[英]How to restrict ngModel changes effect to other inside ng-template in angular7?
[英]Angular: how do I access the reference variable which is in a ng-template
有没有办法访问在 ng-template 元素中声明的#interface?
我必须把 <interface-settings 放在 <ng-template.
因为我需要使用 *ngTemplateOutlet。
由于我找不到解决方案,我必须添加另一个 <interface-settings #interface,而不是在 ng-template 中声明它。
如果您知道其他解决方法,将不胜感激。 谢谢
// 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 中有组件“接口设置”时 - 您的应用程序无法访问/知道它,除非:
例如,类似于您的示例:
<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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.