Javascript 调用子组件的方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31013461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:04:40  来源:igfitidea点击:

Call a method of the child component

javascriptangular

提问by Per Hornsh?j-Schierbeck

I have a nested child component like this:

我有一个这样的嵌套子组件:

<app-main>
    <child-component />
</app-main>

My appMaincomponent needs to invoke a method on child-component.

我的appMain组件需要调用子组件上的方法。

How to invoke a method on the child-component?

如何调用子组件上的方法?

回答by Günter Z?chbauer

You can get a reference to an element using

您可以使用以下方法获取对元素的引用

@ViewChild('childComponent') child;

where childComponentis a template variable <some-elem #childComponent>` or

其中childComponent是模板变量<some-elem #childComponent>` 或

@ViewChild(ComponentType) child;

where ComponentTypeis the type of a component or directive and then in ngAfterViewInitor an event handlers call child.someFunc().

whereComponentType是组件或指令的类型,然后是 inngAfterViewInit或事件处理程序调用child.someFunc()

ngAfterViewInit() {
  console.log(this.child);
}

See also get hold of an element in the template

另请参阅获取模板中的元素

回答by Alexander Ermolov

Parent and child can communicate via data binding.

父子可以通过数据绑定进行通信。

Example:

例子:

@Component({
    selector: 'child-component',
    inputs: ['bar'],
    template: `"{{ bar }}" in child, counter  {{ n }}`
})
class ChildComponent{
    constructor () {
        this.n = 0;
    }
    inc () {
        this.n++;
    }
}

@Component({
    selector: 'my-app',
    template: `
        <child-component #f [bar]="bar"></child-component><br>
        <button (click)="f.inc()">call child func</button>
        <button (click)="bar = 'different'">change parent var</button>
    `,
    directives: [ChildComponent]
})
class AppComponent {
    constructor () {
        this.bar = 'parent var';
    }
}

bootstrap(AppComponent);  

Demo

演示

#fcreates a reference to the child component and can be used in template or passed to function. Data from parent can be passed by [ ]binding.

#f创建对子组件的引用,可以在模板中使用或传递给函数。来自父级的数据可以通过[ ]绑定传递。

回答by Pere Pages

Being a son component

作为子组件

@Component({
    // configuration
    template: `{{data}}`,
    // more configuration
})
export class Son {

  data: number = 3;

  constructor() { }

  updateData(data:number) {
    this.data = data;
  }

}

Having a father component

有父组件

@Component({
    // configuration
})
export class Parent {
  @ViewChild(Son) mySon: Son;

  incrementSonBy5() {
    this.mySon.updateData(this.mySon.data + 5);
  }
}

In the father's template

在父亲的模板中

<son></son>
<button (click)="incrementSonBy5()">Increment son by 5</button>

This solution only works for one <son></son>instance in the parent template. If you have more than one instance only will work in the first one of the template.

此解决方案仅适用<son></son>于父模板中的一个实例。如果您有多个实例,则只能在模板的第一个实例中使用。

回答by Frelseren

The best way to access a child component is @ViewChild.

访问子组件的最佳方式是@ViewChild

Let's say you have AppMainComponent with a nested ChildComponent from your example.

假设您有 AppMainComponent 和示例中的嵌套 ChildComponent。

// app-main.component.ts
import { Component } from '@angular/core';

@Component({
    selector: 'app-main',
    template: `
        <child-component />
    `
})

export class AppMainComponent {}

You want to invoke a clear method from your ChildComponent.

您想从 ChildComponent 调用一个 clear 方法。

// child.component.ts
import { Component } from '@angular/core';

@Component({
    selector: 'child-component',
    template: '{{ greeting }}'
})

class ChildComponent {
    greeting: String = 'Hello World!';

    clear() {
        this.greeting = null;
    }
}

You can accomplish it by importing the ChildComponent class, ViewChild decorator and pass component's class in it as a query. This way, you would have access to the ChildComponent's interface stored in the custom variable. Here is an example:

您可以通过导入 ChildComponent 类、ViewChild 装饰器并在其中将组件的类作为查询传递来完成它。这样,您就可以访问存储在自定义变量中的 ChildComponent 的接口。下面是一个例子:

// app-main.component.ts
import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from './components/child/child.component';

@Component({
    selector: 'app-main',
    template: `
        <child-component />
    `
})

class ChildComponent {
    @ViewChild(ChildComponent)
    child: ChildComponent;

    clearChild() {
        this.child.clear();
    }
}

Notice! Child view becomes available only after ngAfterViewInit.

注意!只有在ngAfterViewInit之后子视图才可用。

Respond after Angular initializes the component's views and child views. Called once after the first ngAfterContentChecked(). A component-only hook.

在 Angular 初始化组件的视图和子视图后响应。在第一个 ngAfterContentChecked() 之后调用一次。仅组件挂钩。

If you want to execute method automatically, you need to do it inside this lifecycle hook.

如果你想自动执行方法,你需要在这个生命周期钩子里做。

You can also get a QueryListof child components via ViewChildrendecorator.

您还可以得到一个QueryList通过子组件ViewChildren装饰。

import { Component, ViewChildren, QueryList } from '@angular/core';
import { ChildComponent } from './components/child/child.component';

...

@ViewChildren(ChildComponent)
children: QueryList<ChildComponent>;

QueryList might be very useful, e.g. you can subscribe for children changes.

QueryList 可能非常有用,例如您可以订阅子项更改。

It's also possible to create template reference variablesand get access to them via the ViewChild decorator.

也可以创建模板引用变量并通过 ViewChild 装饰器访问它们。