angular中@ViewChild 的三种常用方法

//--1------ 在angular中进行dom操作
<div #dom>这是一个div
//放置一个锚点dom import { 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> //在父组件中引入子组件并放置一个锚点 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--; }

你可能感兴趣的:(angular8)