一、子组件调用父组件里面的内容
1、如下面,首先在父组件里面声明一个事件和字符串,需要在子组件里面进行调用
methond(){
alert ("我是父组件");
}
public title:any='我是父组件';
2、然后在父组件里面先引用子组件
[title]和[methond]都是自己命名的,可以进行更改,引号里面的是逻辑端声明出来的。
<app-news2 [title]="title" [methond]='methond'></app-news2>
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();
}
前端代码
<div> {{title}} </div>
<button (click)="methondrun()">
我是子组件
</button>
另外可以把整个父组件传给子组件,把this传进去就可以了。
首先在父组件里使用this
其他内容一样,只不过在声明的时候有所区别,需要用上父组件的名字,下面是调用父组件事件的方法。
二、父组件调用子组件里面内容的方法
1、首先在子组件里面声明一个msg
2、父组件要想使用里面的方法,先引用改子组件
3、然后在父组件里面引用ViewChild
4、前端声明一个方法来获得子组件的内容
逻辑端进行修饰
父组件的前端全部代码
<app-news2 #news2></app-news2>
<button (click)="get()">获取子组件的msg</button>
父组件的逻辑端代码
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);
}
}