angular笔记-组件通信

angular前端组件化思想:将部分模版和逻辑封装为组件,并在不同的页面位置中使用,可以实现代码的复用
angular组件间通信的方式:
@input @output 以及 @ViewChild
一:@input 父传子

//父html文件
<app-child [data]='msg' ></app-child>

//父ts文件
export class Child implements OnInit {
  msg= '100';
  constructor() { }
  ngOnInit() {
  }
}

//子html文件
<p>{{data}}</p>
//子ts文件
import{ Input } from '@angular/core'
@input() data:any;

二:@output 子传父

// 引入Output 与EventEmitter
import {Output ,EventEmitter} from '@angular/core;'
	@Output() private outer = new EventEmitter();
	public msg= '消息'
	child(){
	 this.outer.emit(this.msg); 
	}
	
	//父组件
	<app-child (outer)="getMsg($event)" ></app-child>

三:@ViewChild
第一种父组件直接调用子组件的方法

// 父html文件
<app-child #child></app-child>
<a (click)=‘child.getMsg’ href='javascript:;'></a>

//子ts文件
export class CallRecordComponent implements OnInit {
  constructor(){};
	getMsg(){
	 alert('我是子组件')
	}
}

第二种是父组件间接调用子组件的方法

//父html文件
<app-child #child002></app-child>
<a (click)=‘getMsg002’ href='javascript:;'></a>
//父ts文件
import {ViewChild} form '@angular/core';
	@ViewChild('child002') child002_name;
	getMsg002(){
	 this.child002_name.getMsg();
	}

//子ts文件
export class CallRecordComponent implements OnInit {
  constructor(){};
	getMsg(){
	 alert('我是子组件')
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值