SoFunction
Updated on 2025-04-11

Detailed explanation of DOM operations in components of Angular2 learning tutorial

Preface

Sometimes we have to face some situations where we need to operate the DOM directly in the component. For example, there are a large number of CheckBoxes in our component. We want to get the selected CheckBox. However, these CheckBoxes are generated through loops. We cannot assign an ID to each CheckBox. At this time, it can be achieved by operating the DOM. The angular API contains modifiers such as viewChild, contentChild, etc., which can return the DOM element in the template.

DOM operation in instructions

@Directive({
 selector: 'p'
})
export class TodoDirective{
 constructor(el: ElementRef, renderer: Renderer){
  (, 'backgroundColor', 'red');
 }
}

The above declares a directive, and the use needs to be declared in declarations in module. The purpose of this directive is to set the backgroundColor of the p element to red.

-ElementRef is a class that allows direct access to DOM elements, which contains a nativeElement property. When direct operation of native DOM elements is not allowed, the property value is null.

-Renderer This class contains a large number of methods that can be used to manipulate DOM natively.

@ViewChild and @ViewChildren

Each component has a view template, introduced through template or templateUrl. If you want to get the DOM element in the view template, you can use the @ViewChild and @ViewChildren modifiers. They can accept template variables or element tags or template class names to get the DOM node. @ViewChild returns the ElementRef class reference (the component class name is used directly when obtaining the component), while @ViewChildren returnsQueryList<ElementRef>

//Template content&lt;p *ngFor='let item of todos' #name&gt;{{  }}&lt;/p&gt;

//Get DOM in component@ViewChildren('name')
todoNames: QueryList&lt;ElementRef&gt;;

@ViewChild('name')
todoName: ElementRef;
ngAfterViewInit(){
 (e=&gt;());
 ();
}

@ViewChild('name') and @ViewChildren('name')The p-tagged DOM node can be obtained by obtaining the p-tagged DOM node through the name template variable. You can obtain the node information in the ngAfterViewInit declaration period hook. Of course, it can also be found in other functions, as long as the view is guaranteed to be initialized.

QueryList is an immutable list that contains an Observable variable named changes, so it can be subscribed. Combined with the notifyOnChanges method, you can view the changes in the variables in QueryList in real time. After calling the notifyOnChanges function, when the component's input changes, the Observable will be triggered to issue a new value, so whentodoNames: QueryList<ElementRef>When there is an update, you can view the changes through the following code:

(data => data._results.forEach(
 e=>()));
();

@ContentChild and @ContentChildren

It looks very similar to @ViewChild and @ViewChildren, but @ContentChildren and @ContentChildren are the contents in the component tags and are too lazy to write examples. Here is an example from the official website of angular Chinese:

import {Component, ContentChildren, Directive, Input, QueryList} from '@angular/core';
@Directive({selector: 'pane'})
export class Pane {
 @Input() id: string;
}
@Component({
 selector: 'tab',
 template: `
 <div>panes: {{serializedPanes}}</div> 
 `
})
export class Tab {
 @ContentChildren(Pane) panes: QueryList<Pane>;
 get serializedPanes(): string { return  ? (p => ).join(', ') : ''; }
}
@Component({
 selector: 'example-app',
 template: `
 <tab>
  <pane ></pane>
  <pane ></pane>
  <pane  *ngIf="shouldShow"></pane>
 </tab>
 <button (click)="show()">Show 3</button>
 `,
})
export class ContentChildrenComp {
 shouldShow = false;
 show() {  = true; }
}

It can be seen@ContentChildren(Pane) panes: QueryList<Pane>;What is obtained is the content in the component Tab:

 <tab>
  <pane ></pane>
  <pane ></pane>
  <pane  *ngIf="shouldShow"></pane>
 </tab>

Similar to @ViewChild, @ContentChild gets the first Pane directive. After obtaining the DOM element, it can be processed in a similar way.

Summarize

The above is the entire content of this article. I hope that the content of this article will be of some help to your study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.