angular cli8父组件调用子组件中的方法

1、首先在父组件中引入ViewChild:

import { Component, ViewChild} from '@angular/core';

2、接着在父组件中引入子组件:

import { ChildComponent } from './child/child.component';

3、在父组件通过@ViewChild关联子组件并调用其方法:

// 关联子组件
// 其中{static: false}必须加,旧版本貌似不需要加
@ViewChild('childComponent', {static: false})
public childComponent: ChildComponent;

public childTest() {
	// 调用子组件的方法
	this.childComponent.showTestMessage();
}

4、在父组件的模板中引用子组件:

<child-root #childComponent></child-root>

5、子组件中被调用的方法如下,当父组件的childTest()方法被触发时会执行showTestMessage()方法:

public showTestMessage() {
	alert(1111111);
}

6、如果被调用的组件属于另一个module,则当前组件所在的module需要先引入另一个module。

你可能感兴趣的:(angular)