方法一:
@viewChild 引入子组件
1、传入组件
子组件:
import {Component} from ‘@angular/core‘;
@Component({
selector: ‘app-childen‘,
templateUrl: ‘./user.component.html‘,
styleUrls: [‘./user.component.css‘]
})
export class userFile{
fun1() {
alert(‘子组件方法‘);
}
}
父组件:
import {Component, ViewChild} from ‘@angular/core‘;
import { userFile } from ‘./childen/user.component‘
@Component({
selector: ‘app-parent‘,
templateUrl: ‘./parent.component.html‘,
styleUrls: [‘./parent.component.css‘]
})
export class ParentComponent {
@ViewChild(userFile) user: userFile ;
OnClick() {
this.user.fun1();
}
}
2、传入字符串这种方式是针对指令
import {Component, ViewChild} from ‘@angular/core‘;
@Component({
selector: ‘app-parent‘,
templateUrl: ‘./parent.component.html‘,
styleUrls: [‘./parent.component.css‘]
})
export class ParentComponent {
@ViewChild(‘myChild‘) child;
OnClick() {
this.child.fun1();
}
}
使用方法
<app-component #myCilid></app-component>
方法二 @Input和@Output方法
方法三 局部变量获取子组件
<button (click)=myChild.func1()>提交</button>
<app-component #myCilid></app-component>