ViewChild in Angular

ViewChild in Angular

Use Viewchild in Angular to access a child Component, Director, or DOM Element

Access directive

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); // Dolphin
}
}

Access DOM Element

1
<input #someInput placeholder="Your favorite sea creature">
1
2
3
4
5
6
// ...
@ViewChild('someInput') someInput!: ElementRef;
ngAfterViewInit() {
this.someInput.nativeElement.value = 'Whale!';
}
// ...

Access Child Component

子组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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)

1
<app-child></app-child>

ViewChild访问子组件,并访问其非private方法

1
2
3
4
5
6
// ...
@ViewChild(AppChildComponent) childComp!: AppChildComponent;
ngAfterViewInit() {
console.log(this.childComp.whoAmI()); // I am a pup component!
}
// ...

本文作者: 孟 虎
本文链接: https://menghu1994.github.io/blog/2024/08/Angular/ViewChild/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!