您好,登錄后才能下訂單哦!
這篇文章主要介紹Angular中DOM操作的示例,文中介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們一定要看完!
演示組件:app\components\transition
HTML
<div class="content"> <p>內(nèi)容區(qū)域</p> <div id="box"> this is box </div> <br> <div id="box1" *ngIf="flag"> this is box1 </div> <button (click)="showAside()">彈出側(cè)邊欄</button> <button (click)="hideAside()">隱藏側(cè)邊欄</button> </div> <aside id="aside"> 這是一個側(cè)邊欄 </aside>
組件ts:
public flag:boolean=true; constructor() { } ngOnInit(): void { //組件和指令初始化完成 并不是真正的dom加載完成 let oBox:any=document.getElementById('box'); console.log(oBox.innerHTML); oBox.style.color="red"; //獲取不到dom節(jié)點(diǎn) /* let oBox1:any=document.getElementById('box1'); console.log(oBox1.innerHTML); oBox1.style.color="blue"; */ } //視圖加載完成以后觸發(fā)的方法 dom加載完成 (建議把dom操作放在這個里面) ngAfterViewInit(){ let oBox1:any=document.getElementById('box1'); console.log(oBox1.innerHTML); oBox1.style.color="blue"; } showAside(){ //原生js獲取dom節(jié)點(diǎn) var asideDom:any=document.getElementById('aside'); asideDom.style.transform="translate(0,0)"; } hideAside(){ //原生js獲取dom節(jié)點(diǎn) var asideDom:any=document.getElementById('aside'); asideDom.style.transform="translate(100%,0)"; }
ViewChild:屬性裝飾器
演示文件:\ngDemo\src\app\components\news
1、現(xiàn)在組件模板文件定義屬性 ,通過#
<div #myBox> 我是一個dom節(jié)點(diǎn) </div>
2、現(xiàn)在組件ts通過ViewChild 獲取dom
<div #myBox>我是一個dom節(jié)點(diǎn)</div> <app-header #header></app-header> <button type="button" (click)='getChildProp()'>獲取子組件header的屬性</button> <button type="button" (click)='getChildMethod()'>獲取子組件header的方法</button>
import { Component, OnInit, ViewChild } from '@angular/core'; @Component({ selector: 'app-news', templateUrl: './news.component.html', styleUrls: ['./news.component.less'] }) export class NewsComponent implements OnInit { //獲取Dom @ViewChild('myBox') public myBoxIn: any; @ViewChild('header') public header: any; constructor() { } ngOnInit(): void { // console.log(this.myBoxIn) } //處理dom節(jié)點(diǎn) ngAfterViewInit() { console.log(this.myBoxIn.nativeElement) //父組件獲取到了整個子組件header console.log('父組件獲取到了整個子組件header') console.log(this.header) } //獲取子組件header的屬性 getChildProp() { console.log(this.header.title) } //獲取子組件header的方法 getChildMethod() { console.log(this.header.headRun) this.header.headRun(); } } // 父組件 news 引入 <app-header #header></app-header> // 子組件 header // 父組件 得到 子組件的 數(shù)據(jù) 和 方法 --- 子組件 傳 值給父組件 // 總結(jié): // 1. 父組件中調(diào)用子組件的時候, 給子組件一個名稱 // <app-header #header></app-header> // 2. 在父組件引入viewChild // import { Component, OnInit,ViewChild } from '@angular/core'; // @ViewChild('header') // public header:any; // 3. 已經(jīng)可以在父組件調(diào)用子組件的屬性和方法了 // 父組件傳值給子組件 @input -- 子組件 得到 父組件的 數(shù)據(jù) 和 方法 // 父組件: home // 子組件: header
以上是“Angular中DOM操作的示例”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。