一壤蚜、父組件給子組件傳值 -@Input
- 父組件調(diào)用子組件 的時(shí)候傳入數(shù)據(jù)
<app-header [msg]="msg"></app-header>
- 子組件引入 Input 模塊
import { Component, OnInit ,Input } from '@angular/core';
- 子組件中 @Input 接收父組件傳過來的數(shù)據(jù)
export class HeaderComponent implements OnInit { @Input()
msg:string
constructor() { }
ngOnInit() {
}
}
- 子組件中使用父組 件的數(shù)據(jù)
<h2>這是頭部組件--{{msg}}</h2>
二瘫析、讓子組件執(zhí)行父 組件的方法(父子組件傳值的方式)
- 父組件定義方法
run(){
alert('這是父組件的 run 方法');
}
2.調(diào)用子組件 傳入當(dāng)前方法
<app-header [msg]="msg" [run]="run"></app-header>
- 子組件接收父組件 傳過來的方法
import { Component, OnInit ,Input } from '@angular/core';
@Input() run:any;
export class HeaderComponent implements OnInit {
@Input() msg:string @Input() run:any;
constructor() { } }
- 子組件使用父組件 的方法备蚓。
export class HeaderComponent implements OnInit {
@Input() msg:string; @Input() run:any;
constructor() { } ngOnInit() {
this.run(); /*子組件調(diào)用父組件的 run 方法*/
} }
三恩尾、讓父組件執(zhí)行子組件的方法
- 父組件定義方法(HTML)
<button (click)="myChild.GetTestInfo('我是父組件傳過來的值')">按鈕調(diào)用child2的greeting方法</button>
- 父組件定義方法(TS)
import { ViewChild } from '@angular/core';
@ViewChild(***) auditorListSchedule: **;
- 子組件定義方法(TS)
GetTestInfo(str: string) {
alert('這是子組件的數(shù)據(jù)' + str);
}