如何在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
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:

现在,我们可以访问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 in our template with the #someInput reference variable:

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

app.component.html
app.component.html

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

现在,我们可以使用ViewChild访问并设置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 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组件:

  • 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
child works!

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

你可能感兴趣的:(vue,js,java,python,react)