首頁  >  文章  >  web前端  >  一文聊聊Angular怎麼操作DOM元素

一文聊聊Angular怎麼操作DOM元素

青灯夜游
青灯夜游轉載
2022-01-06 18:58:252431瀏覽

Angular中怎麼操作DOM元素?以下這篇文章跟大家介紹一下angular操作DOM元素的方法,希望對大家有幫助!

一文聊聊Angular怎麼操作DOM元素

在angular取得DOM元素可以使用javascript的原生API,或是引入jQuery透過jquery物件操作DOM ,但angular已經給我們提供了對應的API(ElementRef)來取得DOM元素,就沒必要使用原生的API或jQuery了。 【相關教學推薦:《angular教學》】

ElementRef 取得DOM元素

1、建立TestComponent元件,模板如下:test.component.html

<div>
	<p>你好</p>
</div>
<div>
    <span>世界</span>
</div>
<h1>标题</h1>
<pass-badge id="component" textColor="red">组件</pass-badge>

2、寫test.component.ts檔案

import { Component, OnInit } from &#39;@angular/core&#39;;
// 1、导入 ElementRef 类
import { ElementRef} from &#39;@angular/core&#39;;
import { PassBadge } from &#39;./compoment/pass-badge/pass-badge.component&#39;

@Component({
  selector: &#39;app-test&#39;,
  templateUrl: &#39;./test.component.html&#39;,
  styleUrls: [&#39;./test.component.css&#39;],
  declarations: [ PassBadge ]
})
export class TestComponent implements OnInit {
	// 2、将 ElementRef 类注入 test 组件中
    constructor(private el:ElementRef) {}

    ngOnInit() {
    	// 3、获取 DOM 元素
        console.log(this.el.nativeElement)
        console.log(this.el.nativeElement.querySelector(&#39;#component&#39;))
    }
}

我們來看看this.el.nativeElement是什麼

一文聊聊Angular怎麼操作DOM元素
所以就可以透過this.el.nativeElement.querySelector('#component' )來操作對應的DOM元素。例如改變文字顏色就可以

this.el.nativeElement.querySelector(&#39;#component&#39;).style.color = &#39;lightblue&#39;

模板變數取得DOM元素

#可以透過ViewChild取得元件,同樣的還有ContentChildViewChildrenContentChildren

1、修改TestComponent元件,為對應元素加上範本變數,如下

<div>
    <p>你好</p>
</div>
<!-- 1、给元素加入模板变量 div -->
<div #div>
    <span>世界</span>
</div>
<h1>标题</h1>
<!-- 给组件加入模板变量 component -->
<pass-badge #component textColor="red">组件</pass-badge>

2、修改test.component.ts,如下:

import { Component, OnInit } from &#39;@angular/core&#39;;
import { ElementRef} from &#39;@angular/core&#39;;
// 2、引入ViewChild
import { ViewChild } from &#39;@angular/core&#39;

@Component({
  selector: &#39;app-test&#39;,
  templateUrl: &#39;./test.component.html&#39;,
  styleUrls: [&#39;./test.component.css&#39;]
})
export class TestComponent implements OnInit {
    constructor(private el:ElementRef) {}
    // 3、获取元素
    @ViewChild(&#39;component&#39;) dom: any;
    @ViewChild(&#39;div&#39;) div: any;
    ngOnInit() {
        console.log(this.dom)	// PassBadgeComponent
        this.dom.fn()   // 调用 passbadge 组件的 fn 方法
        console.log(this.div)	// ElementRef
        this.div.nativeElement.style.color = &#39;lightblue&#39;	// 文字颜色修改为淡蓝色
    }
}

最終結果如下

一文聊聊Angular怎麼操作DOM元素

由結果我們可以知道,當使用ViewChild模板變數取得元件元素時,取得到的是元件所導出的元件類別(上例是PassBadgeComponent),這時候只可以操作組件中所含的屬性。

當使用ViewChild模板變數取得html元素時,取得到的時ElementRef類型的類,這時可以透過this.div.nativeElement. querySelector('span')等原生API來操作元素

更多程式相關知識,請造訪:程式設計影片! !

以上是一文聊聊Angular怎麼操作DOM元素的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:csdn.net。如有侵權,請聯絡admin@php.cn刪除