如何在Angular中使用ViewChild访问子组件,伪指令或DOM元素

介绍 (Introduction)

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指令:

  • ng generate directive shark

    ng生成指令鲨鱼

Otherwise, you may need to manually add it to app.module.ts:

否则,您可能需要手动将其添加到app.module.ts

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

shark.directive.ts
鲨鱼指令
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中:

app.component.html
app.component.html
<span appShark>Fin!</span>

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:

现在,我们可以访问SharkDirectivecreature实例变量,并使用其值设置extraCreature实例变量:

app.component.ts
app.component.ts
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 <input> in our template with the #someInput reference variable:

假设我们的模板中有一个<input> ,其中包含#someInput参考变量:

app.component.html
app.component.html
<input #someInput placeholder="Your favorite sea creature">

Now, we can access the <input> with ViewChild and set the value:

现在,我们可以使用ViewChild访问<input>并设置value

app.component.ts
app.component.ts
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 <input> will be set to:

ngAfterViewInit触发时,我们的<input>的值将设置为:


   
   
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组件:

  • ng generate component child --flat

    ng生成子组件--flat

Otherwise, you may need to create child.component.css and child.component.html files and manually add it to app.module.ts:

否则,您可能需要创建child.component.csschild.component.html文件并将其手动添加到app.module.ts

app.module.ts
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 ,它返回一条消息:

child.component.ts
child.component.ts
whoAmI() {
  return 'I am a child component!';
}

Next, we will reference the component in our app template:

接下来,我们将在我们的应用模板中引用该组件:

app.component.html
app.component.html
<app-child>child works!</app-child>

Now, we can call the whoAmI method from within our parent component class with ViewChild like this:

现在,我们可以调用whoAmI我们与父组件类中的方法ViewChild是这样的:

app.component.ts
app.component.ts
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方法。

结论 (Conclusion)

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Angular ,我们可以通过 `@ViewChild` 或 `@ViewChildren` 装饰器来获取组件实例。这两个装饰器的区别在于,`@ViewChild` 获取单个组件实例,而 `@ViewChildren` 获取多个组件实例。 以下是 `@ViewChild` 的使用方法: ```typescript import { Component, ViewChild } from '@angular/core'; import { ChildComponent } from './child.component'; @Component({ selector: 'app-parent', template: ` <app-child></app-child> <button (click)="logChildComponent()">Log Child Component</button> ` }) export class ParentComponent { @ViewChild(ChildComponent) childComponent: ChildComponent; logChildComponent() { console.log(this.childComponent); } } ``` 在上面的示例,我们通过 `@ViewChild` 装饰器获取了 `ChildComponent` 的实例,并将其赋值给了 `childComponent` 属性。在 `logChildComponent()` 方法,我们可以打印出 `ChildComponent` 的实例。 以下是 `@ViewChildren` 的使用方法: ```typescript import { Component, ViewChildren, QueryList } from '@angular/core'; import { ChildComponent } from './child.component'; @Component({ selector: 'app-parent', template: ` <app-child *ngFor="let i of [1, 2, 3]"></app-child> <button (click)="logChildComponents()">Log Child Components</button> ` }) export class ParentComponent { @ViewChildren(ChildComponent) childComponents: QueryList<ChildComponent>; logChildComponents() { console.log(this.childComponents.toArray()); } } ``` 在上面的示例,我们通过 `@ViewChildren` 装饰器获取了所有 `ChildComponent` 的实例,并将其赋值给了 `childComponents` 属性。在 `logChildComponents()` 方法,我们可以打印出所有 `ChildComponent` 的实例。需要注意的是,`@ViewChildren` 装饰器返回的是 `QueryList` 对象,需要通过 `toArray()` 方法将其转换为数组。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值