效果展示:
一、父组件与子组件通讯
首先准备两个组件,aside为父组件,child为子组件,
1、父组件在TS中准备子组件所需的内容
public fatherData:string = '我是父组件的字段';
methodData():void{
console.log('我是父组件的方法');
}
2、挂载(在父组件的HTML中将子组件挂载在其名下,并将子组件所需的内容付给子组件)
<!--[aside]='this'建议此处为父组件的文件名-->
<app-child [fatherData]='fatherData' [methodData]='methodData' [aside]='this'></app-child>
3、在子组件的TS中引入装饰器【input】
import { Component, OnInit, Input } from '@angular/core';
4、在子组件的class类中通过【Input】接收父组件的内容
@Input() fatherData:any;
@Input() methodData:any;
@Input() aside:any;
5、在子组件中创建方法并调用
ceshi():void{
console.log(this.fatherData);
this.methodData();
}
6、在父组件的HTML中调用子组件的方法
<button (click)="ceshi()">父组件调用</button>
二、子组件与父组件通讯
首先准备两个组件,aside为父组件,child为子组件,
1、子组件在TS中准备父组件所需的内容
public fieldData:string = '我是子组件的内容';
method():void{
console.log('我是子组件方法');
}
2、挂载(在子组件的HTML中将子组件挂载在父组件名下,并将父组件所需的内容付给父组件)
<!--关键字:#子组件名-->
<app-child #child></app-child>
3、在父组件的TS中引入装饰器【ViewChild , ElementRef】
import { Component, OnInit, ViewChild , ElementRef } from '@angular/core';
4、在父组件的class类中通过【ViewChild】主动获取子组件的内容
@ViewChild('child',{static:true}) child:any; //关键:@ViewChild('子组件传入的名称',{static:true})
5、在父组件中创建方法
ceshi():void{
this.child.method();
console.log(this.child.fieldData);
}
6、在子组件的HTML中调用父组件的方法
<button (click)="ceshi()">子组件调用</button>