This article will introduce you to Angular’s ViewChild
decorator.
本文将向您介绍Angular的ViewChild
装饰器。
There may be situations where you want to access a directive, child component, or a DOM element from a parent component class. The ViewChild
decorator returns the first element that matches a given directive, component, or template reference selector.
在某些情况下,您想从父组件类访问指令,子组件或DOM元素。 ViewChild
装饰器返回与给定指令,组件或模板引用选择器匹配的第一个元素。
ViewChild
与指令ViewChild
使用 (Using ViewChild
with Directives)ViewChild
makes it possible to access directives.
ViewChild
使访问指令成为可能。
Let’s say we have a SharkDirective
.
假设我们有一个SharkDirective
。
Ideally, you will use @angular/cli
to generate
your directive:
理想情况下,您将使用@angular/cli
generate
指令:
Otherwise, you may need to manually add it to app.module.ts
:
否则,您可能需要手动将其添加到app.module.ts
:
import { SharkDirective } from './shark.directive';
...
@NgModule({
declarations: [
AppComponent,
SharkDirective
],
...
})
Our directive will look for elements with the attribute appShark
and prepend the text in the element with the word Shark
:
我们的指令将查找具有属性appShark
元素,并在元素中的文本前添加Shark
:
import {
Directive,
ElementRef,
Renderer2
} from '@angular/core';
@Directive(
{ selector: '[appShark]' }
)
export class SharkDirective {
creature = 'Dolphin';
constructor(elem: ElementRef, renderer: Renderer2) {
let shark = renderer.createText('Shark ');
renderer.appendChild(elem.nativeElement, shark);
}
}
Next, we will add a Shark
to Fin
by using it in the component template:
接下来,我们将在组件模板中使用“ Shark
添加到Fin
中:
Fin!
When viewing the application in a browser, it will display as:
在浏览器中查看应用程序时,它将显示为:
Output
Shark Fin!
Now, we can access the creature
instance variable of SharkDirective
and set an extraCreature
instance variable with its value:
现在,我们可以访问SharkDirective
的creature
实例变量,并使用其值设置extraCreature
实例变量:
import {
Component,
ViewChild,
AfterViewInit
} from '@angular/core';
import { SharkDirective } from './shark.directive';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
extraCreature: string;
@ViewChild(SharkDirective)
set appShark(directive: SharkDirective) {
this.extraCreature = directive.creature;
};
ngAfterViewInit() {
console.log(this.extraCreature); // Dolphin
}
}
We used a setter here to set the extraCreature
variable. Notice that we wait for the AfterViewInit
lifecycle hook to access our variable, as this is when child components and directives become available.
我们在这里使用了一个setter来设置extraCreature
变量。 注意,我们等待AfterViewInit
生命周期钩子访问变量,因为这是子组件和指令可用时。
When viewing the application in a browser, we will still see the "Shark Fin!"
message. However, in the console log, it will display:
在浏览器中查看应用程序时,我们仍然会看到"Shark Fin!"
信息。 但是,在控制台日志中,它将显示:
Output
Dolphin
The parent component was able to access the value from the directive.
父组件能够从指令访问值。
ViewChild
与DOM元素一起使用 (Using ViewChild
with DOM Elements)ViewChild
makes it possible to access native DOM elements that have a template reference variable.
ViewChild
使访问具有模板引用变量的本机DOM元素成为可能。
Let’s say we have an in our template with the
#someInput
reference variable:
假设我们的模板中有一个 ,其中包含
#someInput
参考变量:
Now, we can access the with
ViewChild
and set the value
:
现在,我们可以使用ViewChild
访问并设置
value
:
import {
Component,
ViewChild,
AfterViewInit,
ElementRef
} from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
@ViewChild('someInput') someInput: ElementRef;
ngAfterViewInit() {
this.someInput.nativeElement.value = 'Whale!';
}
}
When ngAfterViewInit
fires the value of our will be set to:
当ngAfterViewInit
触发时,我们的的值将设置为:
Output
Whale!
The parent component was able to set the value of the child DOM Element.
父组件能够设置子DOM元素的值。
ViewChild
与子组件一起使用 (Using ViewChild
with Child Components)ViewChild
makes it possible to access a child component and call methods or access instance variables that are available to the child.
ViewChild
使访问子组件和调用方法或访问可用于子组件的实例变量成为可能。
Let’s say we have a ChildComponent
. Ideally, you will use @angular/cli
to generate
your component:
假设我们有一个ChildComponent
。 理想情况下,您将使用@angular/cli
generate
组件:
Otherwise, you may need to create child.component.css
and child.component.html
files and manually add it to app.module.ts
:
否则,您可能需要创建child.component.css
和child.component.html
文件并将其手动添加到app.module.ts
:
import { ChildComponent } from './child.component';
...
@NgModule({
declarations: [
AppComponent,
ChildComponent
],
...
})
We will add a whoAmI
method to ChildComponent
which returns a message:
我们将添加一个whoAmI
方法到ChildComponent
,它返回一条消息:
whoAmI() {
return 'I am a child component!';
}
Next, we will reference the component in our app template:
接下来,我们将在我们的应用模板中引用该组件:
child works!
Now, we can call the whoAmI
method from within our parent component class with ViewChild
like this:
现在,我们可以调用whoAmI
我们与父组件类中的方法ViewChild
是这样的:
import {
Component,
ViewChild,
AfterViewInit
} from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements AfterViewInit {
@ViewChild(ChildComponent) child: ChildComponent;
ngAfterViewInit() {
console.log(this.child.whoAmI()); // I am a child component!
}
}
When viewing the application in a browser, the console log will display:
在浏览器中查看应用程序时,控制台日志将显示:
Output
I am a child component!
The parent component was able to call the child component’s whoAmI
method.
父组件能够调用子组件的whoAmI
方法。
You have learned to use ViewChild
to access a directive, child component, and a DOM element from a parent component class.
您已经学习了如何使用ViewChild
从父组件类访问指令,子组件和DOM元素。
If the reference changes to a new element dynamically, ViewChild
will automatically update its reference.
如果引用动态更改为新元素,则ViewChild
将自动更新其引用。
In cases where you’d want to access multiple children, you’d use ViewChildren
instead.
如果要访问多个子级,可以改用ViewChildren
。
If you’d like to learn more about Angular, check out our Angular topic page for exercises and programming projects.
如果您想了解有关Angular的更多信息,请查看我们的Angular主题页面,以获取练习和编程项目。
翻译自: https://www.digitalocean.com/community/tutorials/angular-viewchild-access-component