Angular 2从父级调用子级组件方法 [英] Angular 2 calling a child component method from the parent
问题描述
我尝试使用StackOverflow中建议的不同方法,但无法进行以下工作.
I have tried to use different methods suggested in StackOverflow but I cannot make the following work.
我在ParentComponent中有一个嵌套的ChildComponent.
I have a nested ChildComponent into a ParentComponent.
以下是父级的HTML:
Here the HTML of the parent:
<div> ... <div>
<span *ngIf="value" class="option-button cursor-pointer" [attr.modelURL]="value"
(click)="$event.stopPropagation();getParts(assemblyLibrary)">
<i class="fa fa-cube"></i>
</span>
<child-component></child-component>
很显然,我已将子组件导入到父组件中:
Obviously, I have imported the child component into the parent one:
import { SharedModule } from '../../shared'; //child declaration is inside here
在父组件中,我正在实现以下代码:
in the parent component, I am implementing the following code:
import { child-component } from '../../../child-component';
@Component({
selector: 'parent-component',
templateUrl: './parent-component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ParentComponent implements OnChanges, OnInit {
...
@ViewChild('ChildComponent') childComponent;
openDialog(filesToLoad) {
this.childComponent.openDialog(filesToLoad);
}
getParts(value) {
this.filesToLoad = [];
... code to populate files to load
this.openDialog(this.filesToLoad);
}}
}
当我通过单击HTML中声明的来调用getParts(value)时,出现以下错误:
When I call the getParts(value) by clicking on the declared in my HTML I get the following error:
VM21157:55例外:无法读取未定义的属性'openDialog'
VM21157:55 EXCEPTION: Cannot read property 'openDialog' of undefined
许多用户建议的这种方法有什么问题?
what is wrong with this approach suggested by many users?
推荐答案
父html应该类似于:
Parent html should be like:
<child-component #childComponent></child-component>
然后您可以使用@ViewChild
export class ParentComponent implements OnChanges, OnInit {
...
@ViewChild('childComponent') childComponent;
现在,由于模板中没有#ChildComponent
选择器,因此@ViewChild('ChildComponent') childComponent;
不会选择任何内容.
Right now your @ViewChild('ChildComponent') childComponent;
selects nothing since you don't have a #ChildComponent
selector in your template.
这篇关于Angular 2从父级调用子级组件方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!