// 調用子組件 向子組件傳值和方法的方式
<app-header [title]="title" [run]="run" [parent]="this"></app-header>
在子組件中,引入Input,通過@input() 方式引入,即可通過this.xxx使用
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.less']
})
export class HeaderComponent implements OnInit {
constructor() { }
@Input() title: any;
@Input() run: any;
@Input() parent: any;
ngOnInit() {
}
getPatrent() {
this.run();
this.parent.run(); // 可以直接調用父組件的屬性和方法
}
}
子組件向父組件間傳值
1、通過ViewChild獲取子組件的方法和屬性
import { Component, OnInit, ViewChild } from '@angular/core'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.less'] }) export class HomeComponent implements OnInit { public title: any = '首頁'; @ViewChild('child', {static: false}) child: any; constructor() { } ngOnInit() { } run() { alert('父組件'); } getChildValue() { this.child.childRun(); // 通過這種方式可以獲取到子組件的方法和屬性值 } childFun(e) { console.log(e); } }
2、通過事件廣播
子組件中引入Output和EventEmitter,再使用@Output定義,通過emit分發
父組件中接收(同vue中的emit)