angular之父子组件之间的通信
一、子组件调用父组件里面的内容
1、如下面,首先在父组件里面声明一个事件和字符串,需要在子组件里面进行调用
methond(){alert ("我是父组件");}public title:any='我是父组件';
2、然后在父组件里面先引用子组件
[title]和[methond]都是自己命名的,可以进行更改,引号里面的是逻辑端声明出来的。
3、子组件在逻辑端引入Input。并进行使用
![]()

4、在前端,字段可以直接绑定,事件需要声明一个方法

逻辑端进行调用方法,是在子组件里面声明一个方法,然后调用父组件的方法。
methondrun(){this.methond();}
子组件的全部逻辑代码
import { Component, OnInit ,Input} from '@angular/core';@Component({selector: 'app-news2',templateUrl: './news2.component.html',styleUrls: ['./news2.component.scss']
})
export class News2Component implements OnInit {
public msg:string="我是子组件";constructor() { }ngOnInit(): void {}//接受父组件传来的数据@Input() title:any;@Input() methond:any;@Input() news:any;methondrun(){this.methond();//this.news.methond();}
前端代码
{{title}}
另外可以把整个父组件传给子组件,把this传进去就可以了。
首先在父组件里使用this
![]()
其他内容一样,只不过在声明的时候有所区别,需要用上父组件的名字,下面是调用父组件事件的方法。

二、父组件调用子组件里面内容的方法
1、首先在子组件里面声明一个msg

2、父组件要想使用里面的方法,先引用改子组件

3、然后在父组件里面引用ViewChild
![]()

4、前端声明一个方法来获得子组件的内容

逻辑端进行修饰

父组件的前端全部代码
父组件的逻辑端代码
import { Component, OnInit,ViewChild } from '@angular/core';@Component({selector: 'app-news',templateUrl: './news.component.html',styleUrls: ['./news.component.scss']
})
export class NewsComponent implements OnInit {ngOnInit(): void {}@ViewChild("news2") news2:any;//获取子组件get(){alert(this.news2.msg);}
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
