父组件给子组件传参
//1.子组件通过属性接收父组件传递的参数
//app.component.html
<app-header [title]="name" ></app-header>
//app.component.ts
export class AppComponent {
name:string='我是你爹';
}
//2.子组件引入Input模块
//header.component.ts
import { Component, OnInit ,Input} from '@angular/core';
//3.子组件@input 接收父组件传过来的数据
//header.ts
export class HeaderComponent implements OnInit {
@Input() title:string;
...
}
//4.子组件中使用父组件传递的数据
//header.html
<p>{{title}}</p>
子组件给父组件传参
//1.在父组件创建方法
//app.ts
export class AppComponent {
run(id:string){
console.log(id)
}
}
//app.html
<app-header [title]="name" [run]="run" ></app-header>
//2.子组件引入Input模块
//header.component.ts
import { Component, OnInit ,Input} from '@angular/core';
//3.子组件@input传递参数
//hearder.ts
export class HeaderComponent implements OnInit {
@Input() run:any;
constructor() { }
ngOnInit() {
}
handleClick(){
this.run("1234")
}
}
//header.html
<button (click)="handleClick()">向父传参</button>
子组件通过@output传参
//1.子组件引入模块Output,EventEmitter
//header.ts
import { Component, OnInit ,Input,Output,EventEmitter} from '@angular/core';
//2.子组件中实例化EventEmitter
//header.ts
export class HeaderComponent implements OnInit {
@Output() private outer=new EventEmitter<string>();
...
}
//3.子组件通过EventEmitter实例化的对象outer广播数据
handleClick(){
this.outer.emit("101001")
}
//header.html
<button (click)="handleClick()">向父传参</button>
//4.父组件接收参数
//app.ts
export class AppComponent {
getId(id:string){
console.log(id)
}
}
//app.html
<app-header (outer)="getId($event)"></app-header>