1、父组件给子组件传参(通过属性)

  1. 父组件
  2. //.html
  3. <app-header [title]="title"></app-header>
  1. 父组件
  2. //.ts
  3. export class AppComponent {
  4. public title:string = "我是Html"
  5. }
  1. 子组件通过属性接收父组件传递过来的参数
  2. //子组件中引入Input模块
  3. //.ts
  4. import {Component,OnInit,Input} from '@angular/core'
  5. export class ... {
  6. @Input() title:string;
  7. OnInit(){
  8. }
  9. }
  10. //.html
  11. <p>{{title}}</p>

2、子组件给父组件传参

2-1、方法一(推荐)

  1. //子组件
  2. //.html
  3. <button (click)="handleClick()">向父组件传参</button>
  4. //.ts
  5. import {Component,OnInit,Input} from '@angular/core'
  6. export ... {
  7. @Input() run:any;
  8. ...
  9. handleClick(){
  10. this.run("15345")
  11. }
  12. }
  1. //父组件
  2. //.html
  3. <app-header [title]="title" [run]="run"></app-header>
  4. //.ts
  5. run(id:string){
  6. console.log(id)
  7. }

2-2、方法二(子组件通过@Output向父组件传参)

  1. //泛型:任意类型
  2. class Person<T>{
  3. emit(msg:T){
  4. console.log(msg)
  5. }
  6. }
  7. var p = new Person<string>();
  8. p.emit("hello world")

子组件引入Output,EventEmitter

  1. //子组件
  2. //.html
  3. <button (click)="handleClick()">向父组件传参</button>

子组件中实例化EventEmitter

  1. //.ts
  2. import {Component,OnInit,Input,Output,EventEmitter} from '@angular/core'
  3. export ... {
  4. @Output private outer = new EventEmitter<string>();
  5. handleClick(){
  6. this.outer.emit("556484")
  7. }
  8. }

子组件中通过EventEmitter实例化的对象outer,广播数据

  1. //.ts
  2. export ... {
  3. ...
  4. handleClick(){
  5. this.outer.emit("556484")
  6. }
  7. }

父组件中接收数据

  1. //父组件
  2. //.html
  3. <app-header [title]="title" (outer)="getId($event)"></app-header>
  4. //.ts
  5. export ... {
  6. getId(id:string){
  7. console.log(id)
  8. }
  9. }