ViewChild in Angular
Use Viewchild
in Angular to access a child Component, Director, or DOM Element
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| import {Component, ViewChild, AfterViewInit} from '@angular/core'; import { SharkDirective } from './shark.directive';
@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: [] }) export class AppComponent implements AfterViewInit { extraCreature!: string;
@ViewChild(SharkDirective) set appShark(directive: SharkDirective) { this.extraCreature = directive.creature; };
ngAfterViewInit() { console.log(this.extraCreature); } }
|
Access DOM Element
| <input #someInput placeholder="Your favorite sea creature">
|
| @ViewChild('someInput') someInput!: ElementRef; ngAfterViewInit() { this.someInput.nativeElement.value = 'Whale!'; }
|
Access Child Component
子组件
| import { Component } from '@angular/core';
@Component({ selector: 'app-child', template: `<p>Child Component</p>` }) export class AppChildComponent { whoAmI() { return 'I am a pup component!'; } private mySelf() { return 'I am a private method!,Other component can not access me'; } }
|
父组件中添加子组件(AppChildComponent
)
ViewChild
访问子组件,并访问其非private
方法
| @ViewChild(AppChildComponent) childComp!: AppChildComponent; ngAfterViewInit() { console.log(this.childComp.whoAmI()); }
|