Angular之父组件给子组件传值
父组件给子组件传值 格式
假如定义一个父组件为home 子组件为header代码如下:
父组件html代码:
<app-header [msg]="msg" [run]="run"></app-header>
<br>
------------------
<br>
我是首页组件
父组件component代码:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor() { }
public msg:string="这是父组件的msg";
ngOnInit(): void {
}
public run(){
alert("这是父组件的run方法");
}
}
子组件html代码:
<header>我是头部</header>
<button (click)="getrun()">获取父组件的方法</button>
<button (click)="getmsg()">获取子组件的方法</button>
子组件component代码:
import { Component, OnInit,Input } from '@angular/core';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
constructor() { }
@Input() msg:any;
@Input() run:any;
ngOnInit(): void {
}
public getmsg(){
alert(this.msg)
}
public getrun(){
this.run();
}
}
注意:
1.子组件接收父组件传递值需要和父组件的[名字]一致,
2.子组件接收值需要在component中引入Input模块
3.父组件在传递方法不需要加()