Hi I am new to AngularJs, recently we I review some angular codes, I saw like this:
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, {});
}
}
the reference is : How to make Network visualization work in vis.js with Angular?
So I am confused what is @ViewChild('network', {static: false}) el: ElementRef; For my understanding, viewchild usually used for parent component to call children components. but in this example, I tried to run the code, it works with no child component defined. So here the ElementRef is the "child"?
ViewChild 此处允许您在同一组件中添加对 html 元素的引用在您的情况下,带有 #network 的 div 与 document.getElementById 类似,但它仅检测同一组件中的“子项”
ViewChild is often used to refer to child components. It can also be used to refer to HTML Elements in your template. ElementRef is a way for angular to wrap HTML Elements and manipulate them programmatically. In your example, the <div> is assigned a template variable #network, which is used as a selector to capture that particular <div> in the Component's el property. When you remove the template, the selector returns no Elements, and thus el remains undefined.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.