父组件
1.parent.component.html
<div class="parentBox">
<p>
parent works!
</p>
<!--[]传参 ()传递方法 -->
<app-child #child [fromParent]="parent" (notify)="onNotify($event)"></app-child>
</div>
2.parent.component.ts
import { AfterViewInit, Component, OnInit, ViewChild, ViewChildren } from '@angular/core';
// @viewChild @ViewChildren 时候才需要引入
import { ChildComponent } from '../child/child.component';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
// 自定义变量
private parent = 'this is parent msg';
// 通过模板变量名获取
@ViewChild("child") child: ChildComponent;
@ViewChildren("child") children: ChildComponent;
constructor() { }
ngOnInit() {
}
// @ViewChild和@ViewChildren会在父组件钩子方法ngAfterViewInit调用之前赋值。
ngAfterViewInit() {
console.log(this.child);
console.log(this.children);
}
// 父组件定义方法
private onNotify(data) {
window.alert(`我是父组件的方法啊${data}`);
}
}
子组件
1.child.component.html
<div class="childBox">
<div >
child works!
</div>
<!-- 来自父组件的数据 -->
{{fromParent}}
<!-- 调用父组件的方法并把‘4’传递给父组件 -->
<button (click)="notify.emit(4)">子组件调用父组件的方法</button>
</div>
2.child.component.ts
import { Component, OnInit ,Input, Output, EventEmitter} from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
// 接收参数
@Input() fromParent;
// 调用父组件的方法
@Output() notify = new EventEmitter();
constructor() { }
ngOnInit() {
}
}
效果图:
- @ViewChild @ViewChildren 可查看组件的定义的变量和方法(具体看console里的内容选择使用)
另外,这里是定义了两个模块 ChildModule ParentModule(不是单纯的组件间引用)
子模块 ChildModule
@NgModule({
imports: [
CommonModule
],
declarations: [ChildComponent], // 声明本模块有的组件
exports:[ChildComponent] // 导出供其他模块使用的组件
})
export class ChildModule { }
父模块只需要引入ChildModule 就能使用子模块暴露的组件
不需要引入子模块的组件
import { ChildModule } from '../child/child.module';
@NgModule({
imports: [
CommonModule,
ChildModule, // 引入子模块
ParentRoutingModule
],
declarations: [ParentComponent] // 声明本模块具有的组件
})
export class ParentModule { }