angular @ViewChild使用
生活随笔
收集整理的這篇文章主要介紹了
angular @ViewChild使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 通過@ViewChild獲取子組件,得到子組件的值、調用子組件的方法
//子組件child @Component({selector: 'app-child',templateUrl: './child.component.html',styleUrls: ['./child.component.scss'] }) export class Child{public content:string = '123'public change(){this.content = 'aa'} } //父組件parent <app-child #Children></app-child>import { ViewChild } from '@angular/core'; @Component({selector: 'app-parent',templateUrl: './parent.component.html',styleUrls: ['./parent.component.scss'] }) export class Parent{//通過@ViewChild獲取子組件,得到子組件的值、調用子組件的方法@ViewChild('Children', { static: true }) children: any;public show():void{//獲取子組件的屬性以及方法console.log(this.children.content)this.children.change();} }2.通過@ViewChild獲取某個元素
<p #dom>1111</p> <button (click)="changeColor()">changeColor</button>@ViewChild('dom', { static: true }) eleRef:ElementRef; public changeColor():void{this.eleRef.nativeElement.style.color = 'red'; }對于static,意思就是:如果為true,則在運行更改檢測之前解析查詢結果,如果為false,則在更改檢測之后解析。默認false.
怎么理解呢?
主要就在于“更改檢測”這個動作的發生節點。
例如,我們經常使用到的ngIf、ngShow指令,如果子組件中加入了這些指令,而同時static為true。那么,當我們去捕獲指代目標時,得到的值將是undefined
這塊可能會報錯:Property ‘eleRef’ has no initializer and is not definitely assigned in the constructor.
解決:
- 方法一:在tsconfig.json配置以下設置
- 方法二:使用非空斷言符合!
總結
以上是生活随笔為你收集整理的angular @ViewChild使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: angular中的依赖注入
- 下一篇: angular生命周期钩子ngOnCha