Skip to main content

组件交互

父组件 -> 子组件

子组件定义@Input 属性;父组件传递自己的数组给子组件

子组件 -> 父组件

子组件定义 @Output 属性。

它是一个 EventEmitter 的实例

@Output() public onsubmit = new EventEmitter<number>();
@Output() public cancel = new EventEmitter<void>();

调用.emit(data)传递 data 给父组件

父组件在使用子组件的地方定义一个方法,该方法的参数,就是子组件提交出来的数据

<!-- 注意:模版中如果是eventEmitter的示例则$event是我们emit的数据;如果是原声事件则是Event实例 -->
<app-child (onsubmit)="onUpdate($event)"></app-child>
public onUpdate(num: number) {
console.log(num);
}

@ViewChild

在父组件中通过@ViewChild 选中子组件,可以在父组件的nhAfterViewInit中可以拿到子组件的示例,就可以访问子组件的属性和方法

import { AfterViewInit, ViewChild } from "@angular/core";
import { Component } from "@angular/core";
import { CountdownTimerComponent } from "./countdown-timer.component";

@Component({
selector: "app-countdown-parent-vc",
template: `
<h3>Countdown to Liftoff (via ViewChild)</h3>
<button (click)="start()">Start</button>
<button (click)="stop()">Stop</button>
<div class="seconds">{{ seconds() }}</div>
<app-countdown-timer></app-countdown-timer>
`,
styleUrls: ["../assets/demo.css"]
})
export class CountdownViewChildParentComponent implements AfterViewInit {
@ViewChild(CountdownTimerComponent)
private timerComponent!: CountdownTimerComponent;

seconds() {
return 0;
}

ngAfterViewInit() {
this.seconds = () => this.timerComponent.seconds;
}

start() {
this.timerComponent.start();
}
stop() {
this.timerComponent.stop();
}
}

❗️ 父组件的模版中定义模版变量(#变量名)

import { Component } from "@angular/core";
import { CountdownTimerComponent } from "./countdown-timer.component";

@Component({
selector: "app-countdown-parent-lv",
template: `
<h3>Countdown to Liftoff (via local variable)</h3>
<button (click)="timer.start()">Start</button>
<button (click)="timer.stop()">Stop</button>
<div class="seconds">{{ timer.seconds }}</div>
<app-countdown-timer #timer></app-countdown-timer>
`,
styleUrls: ["../assets/demo.css"]
})
export class CountdownLocalVarParentComponent {}

局限就是只能在父组件的模板中访问子组件的所有属性和方法。父组件本身的代码对子组件没有访问权。

跨组件

service 来实现

父组件和它的子组件共享同一个服务