angular中不同的组件间传值与通信的方法中不同的组件间传值与通信的方法
本文主要介绍angular在不同的组件中如何进行传值,如何通讯。主要分为父子组件和非父子组件部分。
父子组件间参数与通讯方法父子组件间参数与通讯方法
使用事件通信(使用事件通信(EventEmitter,,@Output):):
场景:可以在父子组件之间进行通信,一般使用在子组件传递消息给父组件;
步骤:
子组件创建事件EventEmitter对象,使用@output公开出去;
父组件监听子组件@output出来的方法,然后处理事件。
代码:
// child 组件
@Component({
selector: 'app-child',
template: '',
styles: [``] })
export class AppChildComponent implements OnInit {
@Output() onVoted: EventEmitter<any> = new EventEmitter();
ngOnInit(): void {
this.onVoted.emit(1);
}
}
// parent 组件
@Component({
selector: 'app-parent',
template: `
<app-child (onVoted)="onListen($event)"></app-child>
`,
styles: [``] })
export class AppParentComponent implements OnInit {
ngOnInit(): void {
throw new Error('Method not implemented.');
}
onListen(data: any): void {
console.log('TAG' + '---------->>>' + data);
}
}
使用使用@ViewChild和和@ViewChildren::
场景:一般用于父组件给子组件传递信息,或者父组件调用子组件的方法;
步骤:
父组件里面使用子组件;
父组件里面使用@ViewChild获得子组件对象。
父组件使用子组件对象操控子组件;(传递信息或者调用方法)。
代码:
// 子组件
@Component({
selector: 'app-child',
template: '',
styles: [``] })
export class AppChildComponent2 implements OnInit {
data = 1;
ngOnInit(): void {
}
getData(): void {
console.log('TAG' + '---------->>>' + 111);
}
}
// 父组件
@Component({
selector: 'app-parent2',
template: `
<app-child></app-child>
`,
评论0