angular 父子组件传值及通讯
----------------------------父组件,传递属性到子组件----------------------------------------------------------------- 在子组件应用: @Input() title: any 父组件,传值-----------------------------父组件,传递方法到子组件---------------------------------------------------------------- 父组件,传方法:show 子组件,获取父组件的方法 @Input() run: any //测试方法的传递 test(): void { this.run(); } ---------------------------------父组件,主动调用子组件的属性+方法------------------------------------------- import {Component, OnInit, AfterViewInit, ViewChild} from '@angular/core'; @ViewChild('myheader', {static: true}) myheader: any public ngAfterViewInit() { console.log(this.myheader.aaa) } show() { alert(this.myheader.aaa) this.bbb = this.myheader.aaa }
import {Component, OnInit, Input} from '@angular/core';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
// title = "你好,世界,我是一个头部组件"
@Input() title: any
@Input() run: any
public aaa = "我是header里面的属性";
constructor() {
}
ngOnInit(): void {
}
//测试方法的传递
test(): void {
this.run();
}
test2(): void {
alert(this.aaa)
}
}
header works!
{{title}}
import {Component, OnInit, AfterViewInit, ViewChild} from '@angular/core';
import {SearchService} from '../../services/search.service'
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit {
@ViewChild('myheader', {static: true}) myheader: any
bbb = ''
form = {
name: '',
sex: "1",
city: '',
cityList: ['南昌', '梅州', '深圳'],
loveList: [
{title: '爬山', checked: true},
{title: '篮球', checked: false},
{title: '羽毛球', checked: true},
]
}
sname = ''
constructor(public store: SearchService) {
this.sname = this.store.systemName
}
ngOnInit(): void {
}
public ngAfterViewInit() {
console.log(this.myheader.aaa)
}
show() {
alert(this.myheader.aaa)
this.bbb = this.myheader.aaa
}
}
myheader:{{bbb}} 人员登记系统
{{sname}}
{{form | json}}
- 姓名:
- 性别:男 女
- 所在城市:
- 兴趣爱好: {{item.title}}