Angular - 显示一个字符串 属性,定义在 Child... 在 Parent

Angular - display a string property, defined in Child... in the Parent

如果我有一个在子组件中定义的 属性(字符串),我该如何在父组件中显示它?我看到的所有示例似乎都涉及点击事件/事件发射器。但是如果不需要事件呢?

从 Child 到 Parent

从 child 到 parent 有几种不同的通话方式可供选择,具体取决于用例:

您不应该被 'event' 搞糊涂了。它只是您在 child 中创建的一个事件,作为与 parent 交谈的一种方式。不需要任何用户触发的事件,如点击或任何东西。

有风景Child

在parent.component.ts中:

export class AppComponent implements AfterViewInit {
  value = 'My Value';

  @ViewChild(SecondChildComponent) someChild!: any

  ngAfterViewInit(): void {
    this.value = this.someChild.someValue
  }

在child.component.ts中:

someValue = 'New Value'

这个值只读'AfterViewInit'。 parent 在 child 组件中发生更改时需要某种事件来更新值。

带 EventEmitter 输出

在child.component.ts中:

@Output() someEvent = new EventEmitter

someFunction(): void {
  this.someEvent.emit('Some data...')
}

在 parent 模板中:

<app-child (someEvent)="handleSomeEvent($event)"></app-child>

在parent.component.ts中:

handleSomeEvent(event: any): void {
  // Do something
}

通过路由器插座

我们可以使用 onActivate 方法获取对加载到 router-outlet 中的组件的引用。

在child.component.ts中:


@Output() deleteEvent = new EventEmitter
@Output() addEvent = new EventEmitter

deleteItem(id){
    this.deleteEvent.emit(id)
}
  addItem(data) {
    this.deleteEvent.emit(data)
}

在 parent 模板中:

<router-outlet (activate)="onActivate($event)"></router-outlet>

在parent.component.ts中:

onActivate(componentReference) {
   componentReference.deleteEvent.subscribe((id) => {
      // implementation
   });

   componentReference.addEvent.subscribe((data) => {
      // implementation
   })
}

有服务

我们还可以使用绑定到根的数据服务来在不相关的组件之间共享数据。当许多其他组件需要访问共享数据时,这也很有用。

在役:

private sharedValue = new BehaviorSubject('')
currentSharedValue = this.sharedValue.asObservable()

changeSharedValue(newValue: string) {
  this.sharedValue.next(newValue)
}

组件更改数据:

constructor(
  private dataService: DataService
) { }

changeSharedData(): void {
  this.dataService.changeSharedValue('New Shared Data')
}

读取共享数据的组件:

value = 'Old Value'
subscription!: Subscription;

constructor(
  private dataService: DataService
) { }

ngOnInit() {
  this.subscription = this.dataService.currentSharedValue.subscribe(newValue => {
    this.value = newValue
  })
}

ngOnDestroy() {
  this.subscription.unsubscribe()
}