Angular

Angular與其它前端框架中,關於獲取DOM元素的差異

汪子良 Jonas 2025-11-29
0 136
Angular與其它前端框架中,關於獲取DOM元素的差異

厚厚,第一篇關于技術的文章來了。。。。


個人工作那麼多年,前端三大框架都做過專案,其中,vue和react都是基於VDOM(虛擬DOM的技術),

唯有Angular最為與眾不同,先來快速了解,VDOM是什麼鬼。。。


1,以Js的object來模擬真實的元素,狀態變化並比對差異,若有差異,就render成真實的DOM,如:


const element = {

          elm: 'h1',

          class: {

                color: 'blue'

           },

            ......

}


用法上,以vue為例:

const h1Ref = ref(null);

模版上做綁定:

<h1 ref="h1Ref"></h1>,

腳本裡,透過hook,再賦值給另一全域變數,就可以各種瞎操作。。。

這種方式,不只可以獲取DOM,還可以獲取元件實例,


const h1 = ref(null);

onMounted(() => {

    h1.value = h1Ref.value;

})


2,Angular,就不同了,没有VDOM,直接操作DOM,而獲取DOM元素或元件實例,需要ElementRef這個class,也可以直接用$event這個事件源對象,請看下面最簡單的todolist例子,比如,

addItem後,要如何清空input輸入框的值呢?


app.component.html的程式碼:

<div>
  <input type="text" (input)="onInput($event)">
  <button (click)="addItem()">Add</button>
</div>
<ul>
  <li (click)="removeItem(i)" *ngFor="let item of toDoList; let i = index">
    {{ i + 1 }} -- {{ item }}
  </li>
</ul>


app.component.ts的程式碼:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  // title = 'todo';
  inputValue: string = '';

  inputRef: any;

  constructor() {}
 
  onInput(e: Event) {
    this.inputRef = e.target as HTMLInputElement;
    this.inputValue = (e.target as HTMLInputElement).value;
  }

  addItem() {
    this.toDoList.push(this.inputValue);
    this.inputRef.value = '';
  }

  removeItem(index: number) {
    this.toDoList.splice(index, 1);
  }

  toDoList: string[] = [];
}

 

其中的this.inputRef,就是元素input的dom物件了,其它的元素,以此類推。

Tag: Angular
上一篇
沒有下一篇了

評論列表

這篇文章還沒有任何的評論
weather
臺北 天氣
17℃
心知天氣