在ts文件中使用Angular模板引用变量(#var)的方法

 

在ts文件中使用Angular模板引用变量(#var)的方法

使用井号(#)来声明引用变量。

模板引用变量通常用来引用模板中的某个DOM元素,它可以引用Angular或指令或 Web Component。

我们可以在当前模板的任何地方使用模板引用变量。

示例:

<p-menu #menu [popup]="true" [model]="items"></p-menu>
<button type="button" pButton icon="fa fa-fw fa-list" label="Show" (click)="menu.toggle($event)"></button>

你可以在模板中的任何地方引用模板引用变量。 比如声明在 <p-menu> 上的 menu变量就是在模板另一侧的 <button> 上使用的。

以上是我们使用primeng UI 组件库,弹出菜单的使用方法。

由于有时候我们想要做一些判断,或者右键菜单之类的,就不能直接用这个了。

 

通过前面的示例大家都知道了,primeng  menu菜单弹出都是用的模板引用变量来做的。

因为我们逻辑判断都是在中。因此需要有方法来调用模板引用变量。

这里我们会用到装饰器ViewChild。在模板对应组件TS中定义:

import { Component, ViewChild, AfterViewInit } from '@angular/core';

//假设的。这里引入你用到的menu组件类
import { Menu } from "primeng/menu";

@Component({
selector: 'app-xxx',
templateUrl: './xxx.component.html',
styleUrls: ['./xxx.component.css']
})
export class XXXComponent implements AfterViewInit {

// 菜单组件实例
@ViewChild("rightClicktMenuPopup", { static: true }) rightClicktMenuPopup: Menu;

constructor() {}

ngAfterViewInit(){
//页面组件初始化后调用
this.rightClicktMenuPopup.toggle(event)
}
}

如上所示我们就成功在页面组件初始化后调用了菜单弹出。

如果需要在其他ts中调用,那么需要在其他ts中import 调用这个component即可。