@ViewChild 的三种常用方法
生活随笔
收集整理的這篇文章主要介紹了
@ViewChild 的三种常用方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
//--1------ 在angular中進行dom操作
<div #dom>這是一個div</div> //放置一個錨點domimport { ElementRef, ViewChild } from '@angular/core';@ViewChild('dom',{static:true}), eleRef:ElementRef;
//static-True表示在運行更改檢測之前解析查詢結果,false用于在更改檢測后解析。默認為false。// dom 操作需要在ngAfterViewInit()中進行
// ViewChild會在ngAfterViewInit()回調函數之前做完工作,也就是說你不能在構造函數中使用這個元素。
ngAfterViewInit(){let attr = this.eleRef.nativeElement;console.log(attr) //<div>這是一個div<div>attr.innerHTML = "@ViewChild的dom操作";attr.color = "red";console.log(attr) //<div>@ViewChild的dom操作<div>
}//--2-------通過放置錨點獲取子組件中的方法和屬性
//在子組件中有一個run方法<app-test-it #header></app-test-it> //在父組件中引入子組件并放置一個錨點 header
<button (click)="getSonFn()">點擊獲取子組件里面的方法</button>import {ElementRef,ViewChild} from "angular/core";@ViewChild('header',{static:true}), my:any;getSonFn(){ //這是一個點擊方法,點擊調用這個方法。this.my.run();
}//--3------通過父組件中注入子組件以獲取子組件中的方法和屬性
//子組件中:
<p>{{number}}</p>number:number = 0
addNumber(){this.number++
}//父組件中:
<button (click)="upCount()">number++</button>
<button (click)="downcount()">number--</button>
<app-test-it></app-test-it> //該子組件import {ViewChild} from @angular/core;
import {TestItComponent} from './test/test-it.component";//引入子組件@ViewChild('TestItComponent',{static: ture}) son:TestItComponent; // 核心代碼:用于查詢子組件,并在本地創建的子組件對象 childcomponent 紅注入相同屬性。父組件同樣有兩個方法,自增和自減。upCount(){this.son.addNumber();
}
downCount(){this.son.number--;
}
?
總結
以上是生活随笔為你收集整理的@ViewChild 的三种常用方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Angular自学笔记(?)依赖注入
- 下一篇: angular 内容投影