[英]What is viewchild ElementRef in angular
嗨,我是 AngularJs 的新手,最近我們回顧了一些 Angular 代碼,我看到的是這樣的:
import { Component, AfterViewInit, ElementRef, ViewChild } from '@angular/core';
import { Network, DataSet } from 'vis';
@Component({
selector: 'app-test',
template: '<div #network></div>'
})
export class TestComponent implements AfterViewInit {
@ViewChild('network', {static: false}) el: ElementRef;
private networkInstance: any;
ngAfterViewInit() {
const container = this.el.nativeElement;
const nodes = new DataSet<any>([
{id: 1, label: 'Node 1'},
{id: 2, label: 'Node 2'},
{id: 3, label: 'Node 3'},
{id: 4, label: 'Node 4'},
{id: 5, label: 'Node 5'}
]);
const edges = new DataSet<any>([
{from: 1, to: 3},
{from: 1, to: 2},
{from: 2, to: 4},
{from: 2, to: 5}
]);
const data = { nodes, edges };
this.networkInstance = new Network(container, data, {});
}
}
參考是: 如何使用 Angular 在 vis.js 中使網絡可視化工作?
所以我很困惑什么是@ViewChild('network', {static: false}) el: ElementRef; 據我了解,viewchild 通常用於父組件調用子組件。 但在這個例子中,我試圖運行代碼,它在沒有定義子組件的情況下工作。 那么這里的 ElementRef 是“孩子”嗎?
ViewChild 此處允許您在同一組件中添加對 html 元素的引用在您的情況下,帶有 #network 的 div 與 document.getElementById 類似,但它僅檢測同一組件中的“子項”
ViewChild 常用於引用子組件。 它還可以用於引用模板中的 HTML 元素。 ElementRef 是 angular 包裝 HTML 元素並以編程方式操作它們的一種方式。 在您的示例中, <div> 被分配了一個模板變量 #network,該變量用作選擇器來捕獲組件的 el 屬性中的特定 <div>。 當您刪除模板時,選擇器不返回元素,因此 el 保持未定義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.