相關推薦:《》
演示元件:app\components\transition
HTML
<div class="content"> <p>內容區域</p> <div id="box"> this is box </div> <br> <div id="box1" *ngIf="flag"> this is box1 </div> <button (click)="showAside()">彈出側邊欄</button> <button (click)="hideAside()">隱藏側邊欄</button> </div> <aside id="aside"> 這是一個側邊欄 </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節點 /* let oBox1:any=document.getElementById('box1'); console.log(oBox1.innerHTML); oBox1.style.color="blue"; */ } //檢視載入完成以後觸發的方法 dom載入完成 (建議把dom操作放在這個裡面) ngAfterViewInit(){ let oBox1:any=document.getElementById('box1'); console.log(oBox1.innerHTML); oBox1.style.color="blue"; } showAside(){ //原生js獲取dom節點 var asideDom:any=document.getElementById('aside'); asideDom.style.transform="translate(0,0)"; } hideAside(){ //原生js獲取dom節點 var asideDom:any=document.getElementById('aside'); asideDom.style.transform="translate(100%,0)"; }
ViewChild:屬性裝飾器
演示檔案:\ngDemo\src\app\components\news
1、現在元件模板檔案定義屬性 ,通過#
<div #myBox> 我是一個dom節點 </div>
2、現在元件ts通過ViewChild 獲取dom
<div #myBox>我是一個dom節點</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節點 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 // 父元件 得到 子元件的 資料 和 方法 --- 子元件 傳 值給父元件 // 總結: // 1. 父元件中呼叫子元件的時候, 給子元件一個名稱 // <app-header #header></app-header> // 2. 在父元件引入viewChild // import { Component, OnInit,ViewChild } from '@angular/core'; // @ViewChild('header') // public header:any; // 3. 已經可以在父元件呼叫子元件的屬性和方法了 // 父元件傳值給子元件 @input -- 子元件 得到 父元件的 資料 和 方法 // 父元件: home // 子元件: header
更多程式設計相關知識,請存取:!!
以上就是淺談Angular中的DOM操作的詳細內容,更多請關注TW511.COM其它相關文章!