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