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);
  }

}

转载于:https://www.cnblogs.com/kbinblog/p/11558422.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值