Angular 组件间的交互

父组件向子组件传值-@Input

思路

  • 子组件使用@Input来接收父组件传过来的值 通过父组件定义的变量来接收
  • 父组件在子组件模板中绑定要传递的值 并定义要传递的值 如 [paramOne]是传递的变量 'paramOneVal' 是传递的值

代码

<div>
  <h1>父组件</h1>
  <hr>
  <app-child-component [paramOne]='paramOneVal' [paramTwo]='paramTwoVal' ></app-child-component>
</div>
export class ParentComponentComponent implements OnInit {
  public paramOneVal; // 向子组件传值
  public paramTwoVal;
  constructor() { }
  ngOnInit() {
    this.paramOneVal = '父组件传过来的paramTwo';
    this.paramTwoVal = '父组件传过来的paramTwo';
  }
}

<div>
  <h1>子组件</h1>
  <p>{{paramOne}}</p>
  <p>{{paramTwo}}</p>
</div>  

export class ChildComponentComponent implements OnInit {
  @Input() paramOne: string; // 接收父组件传过来的值
  @Input() paramTwo: string;
  constructor() { }
  ngOnInit() {
  }

}

父组件向子组件传值-#child

思路

  • 父组件通过调用子组件的方法来传值
  • 子组件添加要被调用的方法
  • 父组件在子组件的模板中加入本地变量(#child)然后通过这个本地变量去调用子组件的方法并传值
  • 不一定是点击事件 你只要有触发的条件即可

代码

//子组件
export class ChildComponentComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }
  greeting(name: string) {
    console.log('hello' + name);
  }
}
//父组件
<app-child-component #child></app-child-component>
<button (click)="sendToChild()">点击</button>
export class PartentComponentComponent implements OnInit {
  @ViewChild(ChildComponentComponent, {static: false})
  private child: ChildComponentComponent;
  constructor() { }
  ngOnInit() {
  }
  sendToChild(){
    this.child.greeting('kobe');
  }
}

子组件向父组件传值- EventEmitter

思路

  • 子组件定义一个EventEmitter对象的变量 并通过该变量的emit方法来向子组件传值
  • 父组件在子组件的模板上定义一个接收值的方法 方法类型就是子组件定义的EventEmitter变量
  • 最后父组件通过定义的函数来接收值

代码

//子组件
export class Child1ComponentComponent implements OnInit {
  @Output() initEmit = new EventEmitter();
  constructor() { }
  ngOnInit() {
    this.initEmit.emit('子组件传过来的值');
  }
}
//父组件
<app-child1-component (initEmit)="getChildData($event)"></app-child1-component>
export class App1ComponentComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }
  getChildData(msg: string) {
    console.log(msg);
  }
}
posted @ 2019-09-20 17:19  Kbin24  阅读(505)  评论(0编辑  收藏  举报