Angular
Angular與其它前端框架中,關於獲取DOM元素的差異
0
136
厚厚,第一篇關于技術的文章來了。。。。
個人工作那麼多年,前端三大框架都做過專案,其中,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
上一篇
沒有下一篇了
上一篇
【分享】這才是張一鳴的真面目
沒有下一篇了
Jonas
熱愛程式設計、英語、天文、旅游、電影、乒乓球與曳步舞,興趣廣泛。。。
評論列表
這篇文章還沒有任何的評論