父组件:Home 子组件:Header
app.component.html:
<app-home></app-home>
home.component.html:
<app-header [title]="title" [msg]="msg"
[run]='run'
[home]='this'
></app-header>
<br>
<hr>
<div>我是一个home组件</div>
home.component.ts:
import { Component, OnInit} from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
public title:any="首页组件的标题";
public msg:any="我是父组件的msg";
run(){
alert('我是父组件的run方法')
}
constructor() { }
ngOnInit() {
}
}
header.component.html:
<header>{{title}}-----{{msg}}</header>
<br>
<button (click)="getParentMsg()">子组件里面获取父组件传入的msg </button>
<br>
<button (click)="getParentRun()">子组件里面执行父组件的run方法</button>
header.component.ts:
import { Component, OnInit,Input } from '@angular/core';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
@Input() title:any;
@Input() msg:any;
@Input() run:any;
@Input() home:any;
getParentMsg(){
alert(this.msg)
}
getParentRun(){
this.run()
console.log(this.home.msg);
this.home.run();
}
constructor() { }
ngOnInit() {
}
}